What is the difference between int and variable with php casting?

Asked

Viewed 136 times

2

I am developing a small system that includes javascript and php code, linked to Mysql. I’m trying to send a code that will be set in JS as an argument for a php function.

However, when I test the function with a variable in the SQL search does not work, even if it is an integer variable (tests inserting a normal number in place of the variable work perfectly).

function buscar_informacoes($conexao, $codigo){

    $codigo_numerico = (int)$codigo;

    echo "Código recebido tem o tipo " . gettype($codigo) . "<br>";
    //-> Retorna String

    echo "Código alterado tem o tipo " . gettype($codigo_numerico);
    //-> Retorna Integer

    $sqlBusca = "SELECT * FROM tbl_jogos 
                WHERE codigo = $codigo_numerico ; " ;

    //Quando insere número, funciona normalmente
    //Colocando o argumento recebido, não funciona, possui tipo String
    //Colocando uma variável que sofreu casting para int, não funciona

    $resultado = mysqli_query($conexao, $sqlBusca);

    $informacoes_jogo = array();

    if($sqlBusca === FALSE) { 
        die(mysqli_error());
    }

    while ($informacao = mysqli_fetch_assoc($resultado)) {
        array_push($informacoes_jogo, $informacao);
    }

    return $informacoes_jogo;
    //-> Atualmente retorna: array(0) { } 
}

The question you don’t want to shut up: why entering a number in the SQL command works and a variable that has an int value obtained from a casting no?

Thanks in advance!

Edit

Query with execution in php:

array(1) { [0]=> array(8) { ["code"]=> string(1) "1" ["name"]=> string(10) "God of War" ["gender"]=> string(15) "Action/Adventure" ["classificaca_indicative"]=> string(40) "Not recommended for children under 18" ["language"]=> string(18) "English/Portuguese" ["platform"]=> string(13) "PlayStation 4" ["mark"]=> string(25) "Playstation - Sony Brasil" ["price"]=> string(6) "148.72" } }

  • Considering the situation where "it does not work": 1) What is the value of $codigo_numerico? 2) What is the final value of $sqlBusca? 3) What is the error message? (If it does not appear on the screen, check the server log)

  • The value of $numeric code is an integer, it can be any one, because it will be multiple passcodes. The test can be done with any integer value. The desirable return of $sqlBusca is an 8 element associative array, including testing the code in the Mysql database works normally. There is no error message, it returns an array, but an empty array.

  • Run directly into the bank SELECT * FROM tbl_jogos WHERE codigo = 1;, what is the result? (add to question) And if you do $codigo_numerico = 1 and execute SELECT * FROM tbl_jogos WHERE codigo = $codigo_numerico ;, what is the result? (add to question)

  • Consulta em banco: &#xA;| codigo | nome | genero | classificacao_indicativa | idioma | plataforma | marca | preco |&#xA;| 1 | God of War | Action/Adventure | Not recommended for children under 18 | English/Portuguese | Playstation 4 | Playstation - Sony United States | 148.72 |

  • Query with execution in php: array(1) { [0]=> array(8) { ["code"]=> string(1) "1" ["name"]=> string(10) "God of War" ["gender"]=> string(15) "Action/Adventure" ["classificaca_indicative"]=> string(40) "Not recommended for children under 18" ["language"]=> string(18) "English/Portuguese" ["platform"]=> string(13) "PlayStation 4" ["mark"]=> string(25) "Playstation - Sony Brasil" ["price"]=> string(6) "148.72" } }

  • There is the [Edit] button to change the question

  • Other than that, the results were apparently the same. So what really is the problem?

  • The problem is that there is no way to set the integer value in the variable, as done in $numeric code = 1, because this value is received as argument in String format, as "1". Therefore, the $numeric code could receive the argument with the casting, as $codigo_numero = (int)$argumentString, but this way does not work in the sql query. The doubt is the difference between setting $numeric code = 1 or $codigo_numero = (int)$argumentString this way, because the search only happens effectively in the first option.

  • There is no difference if the string received is actually "1". Incidentally, the casting nor is it necessary for consultation.

Show 4 more comments

1 answer

0

To solve this problem and bring more security to your code, use Prepared statements.

function buscar_informacoes($conexao, $codigo) {

    if ($conexao->connect_errno) {
        die('Could not connect: ' . $conn->connect_error);
    }

    $informacoes_jogo = array();

    $stmt = $conexao->prepare('SELECT * FROM tbl_jogos WHERE codigo = ?');
    $stmt->bind_param('s', $codigo);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($informacao = $result->fetch_assoc()) {
        $informacoes_jogo[] = $informacao;
    }

    $stmt->close();        

    return $informacoes_jogo;
}
  • Thanks for the tip! The code looked much better but didn’t work, keeps returning an empty array when made the request.

  • Then there is something wrong between the PHP communication enter the database. Check whether the object parameters $conexao are correct and "pointing" to the right destination.

  • The communication is correct, because if, for example, internally in the code I set $code = "2", it reads normally and returns the array. But if I assign direct, as in suggested code, it does not work.

  • Strange... but try it this way to see if it solves your problem: "SELECT * FROM tbl_jogos WHERE codigo = '?'"

  • Unsuccessful. Generated message: mysqli_stmt::bind_param(): Number of variables doesn’t match number of Parameters in Prepared statement in

Browser other questions tagged

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