Check whether $_GET value is 1 or 2 and run SQL UPDATE

Asked

Viewed 480 times

3

I have the $_GET['id'] and I need to check if the value it takes from the url index.php?id= is 1 or 2, and if none of the alternatives runs a die();, if it is 1 or 2 assigning $var = $_GET['id']; and with a if calls each of the operations for each id specifies and executes the SQL operation, which is not being executed.

Complete code:

    //Verifica se id é 1 ou 2
    if (!preg_match('/^[1-2]/', $_GET['id'])) {
        die();// not valid
    } else {
        $var = $_GET['id'];
    }

    //Recebe outros dados do index.php via post
    $pk = $_POST['pk'];
    $name = $_POST['name'];
    $value = $_POST['value'];

    $conn = new PDO('mysql:dbname=my_database;host=127.0.0.1', 'root', '');
    //$conn->exec("SET CHARACTER SET utf8"); #Estava em um exemplo, não sei se é necessario aqui

    //index.php?id=1
    if($var == "1"){
        //Executa SQL
        $sql = "UPDATE table_1 ".
        "SET :name=':value' ".
        "WHERE name_id = ':pk'";
    }   
    else
    {
        die("ERRO #1");
    }

    //index.php?id=2
    if($var == "2"){
        //Executa SQL2
        $sql = "UPDATE table_2 ".
        "SET :name=':value' ".
        "WHERE name_id = ':pk'";
    }   
    else
    {
        die("ERRO #2");
    }

    $statement = $conn->prepare($sql);
    $statement->bindValue(":pk", $pk);
    $statement->bindValue(":name", $name);
    $statement->bindValue(":value", $value);
    $count = $statement->execute();

Debug: Returns ERRO #2 when should I return ERRO #1 in the operation 1. (Inverted)

3 answers

4


For this there is the elseif:

if($var == "1"){
   $sql = "UPDATE table_1 ".
      "SET :name=':value' ".
      "WHERE name_id = ':pk'";
}   
elseif($var == "2"){ // esta condição será testada se o if de cima for falso
   $sql = "UPDATE table_2 ".
      "SET :name=':value' ".
      "WHERE name_id = ':pk'";
}   
else
{
   die("ERRO #2");
}


Applying to your code, and eliminating a preg_match() unnecessary:

Since you are just creating the $sql strings, just start PHP with this part, this if completely eliminates the use of preg_match(), greatly simplifying your page.

$var = @$_GET['id']; // Usamos a @ pra suprimir alertas, já que o valor será verificado

if($var == "1"){
   $sql = "UPDATE table_1 ".
      "SET :name=':value' ".
      "WHERE name_id = ':pk'";
}   
elseif($var == "2")
{
   $sql = "UPDATE table_2 ".
      "SET :name=':value' ".
      "WHERE name_id = ':pk'";
}   
else
{
   die( 'ERRO' );
}

$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];

$conn = new PDO( 'mysql:dbname=my_database;host=127.0.0.1', 'root', '' );

$statement = $conn->prepare( $sql );
$statement->bindValue( ':pk', $pk );
$statement->bindValue( ':name', $name );
$statement->bindValue( ':value', $value );
$count = $statement->execute();

If you want to simplify it further:

if($var == "1") {
   $sql = "UPDATE table_1 " // Estou assumindo que o nome da tabela possa ser outro
} elseif($var == "2") {
   $sql = "UPDATE table_2 " // Senao bastaria um 'UPDATE table_'.$var em vez de if
} else {
   die( 'ERRO' );
}
$sql .= " SET :name=':value' WHERE name_id = ':pk'"; // Completamos qualquer update aqui


Knowing the switch:

An alternative would be to use switch, but it would be exaggerated in your case, with only 2 items. I put here just so you know that is an alternative to if and elseif.

switch ($i) {
   case 1:
      //Executa SQL
      $sql = "UPDATE table_1 ".
      "SET :name=':value' ".
      "WHERE name_id = ':pk'";
      break;
   case 2:
      //Executa SQL2
      $sql = "UPDATE table_2 ".
      "SET :name=':value' ".
      "WHERE name_id = ':pk'";
      break;
   default:
       echo "#ERRO";
}

One of the advantages of switch is when you need to do the same action for 2 or 3 items in a row, omitting the break. It’s not your case.

  • Thank you for editing, demonstrated your real interest in helping. @Bacco, if possible could you explain this to me $count, if he is not needed there, why is he? What is he for exactly?

  • @Florida for me does not make sense a variable with that name. o execute will return true whether the operation was successful, or false otherwise.

3

Seems to be a logic error in the code. The code only accepts 2 values in the parameter id, depending on the function preg_match. After this line the $_GET['id'] will only be 1 or 2, theoretically if the $_GET['id'] for 2, the if ($var == "2") will never run because the script dies with the message ERRO #1. If $_GET['id'] is already 1, the script falls into the first else after the if ($var == "1") returning ERRO #2. If you want ERRO #1 for when the parameter is 1, shall invert the messages.

2

Let’s go in pieces...

Use preg_match() for this type of simple check is the same as killing an ant with a cannonball. With a little more programming logic, basic that any programmer should have, applied the syntax of PHP, you would arrive at something like:

$id = ( isset( $_GET['id'] ) ? (int) $_GET['id'] : NULL )

if( $id != 1 || $id != 2 ) {

    die( 'Message Here' );
}

By itself this should already work, allowing, including that else of your SQL Statement has been removed. Unless, of course, you really need to distinguish the messages.

However, this amounts to covering the sun with a sieve. The correct is first of all you structure the routes of your application in a logical and hierarchical way.

If you start now to condition multiple possibilities of SQL in the same routine, it doesn’t take long you will have a single routine of more than 500 lines, full of comments (not that commenting is something bad).

So if you have two different actions, separate them, for example:

Current: index.php?id=1 and index.php?id=2 Improved: action1.php and action2.php

Note: Although "improved", it is not yet ideal, but the example here is didactic and aims only to clarify the concept of separation.

  • I appreciate the suggestion, I will make use of it, but in this case it would be more like having the two actions in a script, saves work if any small change has to be made, in which case it would only do 1 time instead of in the 2 files.

  • 1

    Understandable, but I hope you don’t forget in the future :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.