Check if $ _GET value is 1 or 2 and execute SQL UPDATE

3

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

Full 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 it should return ERRO #1 in operation 1 . (Inverted)

    
asked by anonymous 10.06.2014 / 18:46

3 answers

4

For this there is 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 deleting an unnecessary preg_match() :

As you are just creating the $ sql strings, just start PHP with this part, that 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 switch :

An alternative would be to switch , but would be exaggerated in your case, with only 2 items. I put it here just so you know it's 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 break . It's not your case.

    
10.06.2014 / 19:24
3

It seems to be a logic bug in the code. The code only accepts 2 values in the id parameter, according to the preg_match function. After this line the $_GET['id'] will only be 1 or 2, theoretically if the $_GET['id'] is 2, the if ($var == "2") will never be executed because the script dies with the message ERRO #1 . If $ _GET ['id'] is 1 , then the script drops to the first else after if ($var == "1") returning ERRO #2 . If you want ERRO #1 for when the paramenter is 1 , you should reverse the messages.

    
10.06.2014 / 19:17
2

Let's go by parts ...

Using 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 come up with something like:

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

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

    die( 'Message Here' );
}

This should already work, allowing even that else of your SQL Statement to be removed. Unless, of course, you really have to distinguish the messages.

However, this is equivalent to covering the sun with a sieve. The correct thing is first of all you structure the routes of your Application logically and hierarchically.

If you now start conditioning multiple SQL possibilities in the same routine, it will not take long for you to have a single routine of more than 500 rows, full of comments (not to mention something bad).

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

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

  

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

    
10.06.2014 / 19:34