The query does not work, it does not detect letters

4

I'm trying to do a query in PHP and MYSQL, but it does not work for me,

'grado' is a number, for example 2. If I make the query only with 'grado' if it works, but if I try with 'grupo' which is a letter, for example B, it does not work, it is as if it did not detect the letters of the alphabet.

$grado=$_GET['grado']; 
$grupo=$_GET['grupo']; 
$sql = "* FROM usuarios WHERE grado = $grado  AND grupo = $grupo";
$result = $conn->query($sql);
    
asked by JESUS ESPINOSA 09.02.2016 в 15:58
source

3 answers

6

The problem is that you are not escaping the lyrics. Your query should look like this:

$sql = "SELECT * FROM usuarios WHERE grado = $grado  AND grupo = '$grupo'";
//---------------------------------------------------------------^------^

Anyway, it would be better if your query is executed in a prepared way and not directly:

$sql = "SELECT * FROM usuarios WHERE grado = ? AND grupo = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $grado, $grupo);

This way you avoid SQL injection problems in your application.

    
answered by 09.02.2016 / 16:02
source
2

The texts have to be enclosed with single quotes:

$sql = "* FROM usuarios WHERE grado = $grado AND grupo = '$grupo'";

In any case you'd better make sure that both $grado , as $grupo are safe before putting them in the query.

There is a fairly serious security flaw called SQL Injection that would allow you to run random queries on your portal.

    
answered by 09.02.2016 в 16:03
1

Have you tried it this way?

$grado = $_GET['grado'];
$grupo = $_GET['grupo'];

if ( isset($grado) && isset($grupo) ) {

    $sql = "* FROM usuarios WHERE grado = ".$grado."  AND grupo = ".$grupo;

    if ( $result = $conn - > query($sql) ) {
        echo 'Correcto'; // funciona....
    };

} else {
    echo 'fallo en parametros';
}
    
answered by 09.02.2016 в 16:46