Doubts in PHP and SQL Ready Queries, SELECT Statement and Show Data

0

I try to update some systems that I have created, in which I try to add consultas preparadas to improve mainly the security.

I'm trying to do a SELECT and it's not clear to me how I could go through it.

$sql = "SELECT * FROM clientes WHERE id_cliente = ?";

$resultado = mysqli_prepare($mysqli, $sql);
$ok = mysqli_stmt_bind_param($resultado, "i", $id_cliente);
$ok = mysqli_stmt_execute($resultado);

I've thought about doing this, and I've come this far.

  • Is it a good way? or .. Could I do the query in a better way?
  • How can I go through it with a while? to show for example

row['nombre'];

Thanks, and apologize, if for some it is very basic, but I had not touched almost anything so far the prepared statments .

    
asked by Javier Avila Fernandez 08.09.2018 в 15:46
source

1 answer

1

Good morning, I'll leave you a code so you can guide yourself:

$sql = "SELECT campo1, campo2 FROM clientes WHERE id_cliente = ?";
$sentencia= mysqli_prepare($sql);
$sentencia->bind_param('i', $idCLiente);
$idCLiente = 12;

$sentencia->execute();  

// Vinculamos variables a campos
$sentencia->bind_result($campo1, $campo2);

// Obtenemos los valores
while ($sentencia->fetch()) {
  printf("%s %s\n", $campo1, $campo2);
}

// Cerramos la sentencia preparada
$sentencia->close();  

Explanation:

$ sql would be the variable where you indicate your query or sql query, then we call the mysqli_prepare method to indicate that it is a prepared query, then we link the sign (s) of interrogation with the variable or variables that the filters will have for your query in this case $ idCliente , that's why we place bind_param . If you notice there is a 'i' before the variable $ idCliente , that is to indicate the type of data, in this case int , if you need to pass more filters it would look like this:

$sql = "SELECT campo1, campo2 FROM clientes WHERE id_cliente = ? AND idOtro = ? AND nombre = ?";
$sentencia= mysqli_prepare($sql);
$sentencia->bind_param('iis', $idCLiente,$idOtro,$nombre);

If you notice now this 'iis' which means that they will be two integers and a string. Then you indicate the values of the linked variables.

Then to go through the result you must specify the value of the fields obtained for that we use the bind_result where we will store the values of those fields in some variables and then you can go through it with a while .

I hope it serves you.

    
answered by 08.09.2018 / 19:15
source