mysqli is a bit different from PDO and that shows in the prepared queries.
The things that differ are:
-
mysqli does not support :nombre markers, you must use placeholders ?
- to do the binding you must use
bind_param , with two types of parameters: to the left the data type of each column, to the right the value of the column. See in its link how it is used when there are several columns of several types of data. Here I put a s assuming that the column rut is of type VARCHAR
- to read the data, the methods
fetch specific to mysqli are used ... there are several, as in PDO, but the syntax is different. But in mysqli the ease with which the data is recovered in this type of queries when using PDO is missed. In fact, to obtain associative results in prepared queries, if you do not have the mysqlnd driver installed, that process that seems so simple is complicated.
Knowing that, I propose three solutions:
Solution 1
You can retrieve the results by using the bind_result method It can be interesting when there are few columns in the SELECT . Of course, you have to indicate explicitly the columns you want to assign each one to a variable. In any case, it is always convenient to indicate explicitly the columns that we want to select, avoiding the use of SELECT * :
$sql="SELECT nombre, rut FROM usuario WHERE rut = ?";
if ($stmt = $conn->prepare($sql)){
$stmt->bind_param('s',$Codigo);
$stmt->bind_result($nombre, $rut);
$stmt->execute();
while ($stmt->fetch) {
echo $rut."*".$rut."*".$nombre;
}
}else{
echo "Error en la consulta: ";
}
The problem of bind_result is that when there are many columns you have to do the binding one by one.
Solution 2
You can use something similar to the PDO associative array result, using fetch_assoc combined with get_result . Only this last function is linked to drive mysqlnd . If it is not installed this code will not work:
$sql="SELECT nombre, rut FROM usuario WHERE rut = ?";
if ($stmt = $conn->prepare($sql)){
$stmt->bind_param('s',$Codigo);
$stmt->bind_result($nombre, $rut);
$stmt->execute();
$datos = $stmt->get_result(); //requiere mysqlnd
while ( $row = $datos->fetch_assoc() ) {
echo $row['rut']."*".$row['rut']."*".$row['nombres'];
}
}else{
echo "Error en la consulta: ";
}
Solution 3:
Implement your own function that emulates get_result . This is particularly useful when you need to move the results elsewhere. Or when you work on a 'SELECT with several columns.
More details on this third way are explained here: