Error in mysql query with php

1
$re=mysql_query(
                "select * from productos where id=".$_GET['id']
                )
                or die (mysql_error());

This upper line gives me this error, but I can not find it:

  

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

    
asked by racxo 23.03.2017 в 13:31
source

1 answer

7

Your code has several problems:

  • You are using direct interpolation of variables in a sentence
  • You are using an obsolete connector
  • You are directly using a superglobal variable without checking if it exists
  • You are using die() instead of exceptions

However, all that goes on the side of good practices. Assuming that you do not intend to change your practices, the specific error can be debugged by doing:

$sentencia="select * from productos where id=".$_GET['id'];
print_r($sentencia);
$re=mysql_query($sentencia)  or die (mysql_error());

That does not solve your problem, but it is the way for you to diagnose yourself what you are going to mysql_query instead of simply assume that "you can not find the error".

Recommendation

Do not use the php_mysql connector. Use PDO or MySQLi. Use prepared statements instead of direct interpolation of variables. Check the existence of a superglobal instead of using it directly. Use exceptions instead of die() .

How would it look like with PDO:

if(!isset($_GET['id']) ){ // <-- compruebo la existencia de la superglobal

    echo 'No está fijado el parámetro "id"';

} else {

    $id = $_GET['id'];

    $sentencia="select * from productos where id=:id";

    $stmt = $conn->prepare($sentencia); // <-- uso una sentencia preparada

    try {

        $stmt->execute([':id'=>$id]); // <-- PDO sanitiza el parámetro $id

    } catch (\PDOException $e) {

        echo 'Ocurrió un error en la consulta: '.$e->getMessage();

    }

}
    
answered by 23.03.2017 в 13:45