Query ready MySQLi

2

Good people I want to ask a question about How to translate this code in PDO to MySQLi ? I'm having problems how to take it to MySQLi any ideas. Greetings.

$stmt = $conn->prepare("SELECT * FROM usuario WHERE rut = :codigo");
$stmt->bindParam(':codigo',$Codigo);
$stmt->execute();
if($row = $stmt->fetch()){
    echo $row['rut']."*".$row['rut']."*".$row['nombres'];
}
    
asked by Felipe Larraguibel 30.10.2018 в 15:18
source

3 answers

0

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:

answered by 30.10.2018 / 15:27
source
0

You should try this way

$stmt = $conn->prepare("SELECT * FROM usuario WHERE rut = ?");
$stmt->bind_param('s',$Codigo);
$stmt->execute();

while($fila = mysqli_fetch_assoc($stmt))
{
    echo $fila['rut']."*".$fila['rut']."*".$fila['nombres'];
}

OBSERVATIONS

  • In mysqli the bookmarks are with the symbol of: ? and are known as placeholders
  • the binning method is written like this: bind_param() receives as first argument between quotes s identifying if it is a string or i if it is an integer and then the variable
  • later you use the execute() method
  • To go through all the registers we can use a while, where we declare a variable $fila which we match with the mysqli_fetch_assoc() method and we pass the variable $stmt
  • Finally with a echo we print, from the variable row, each column that you are reading
  • answered by 30.10.2018 в 15:31
    0

    would be more or less like that

    $stmt = $conn->prepare("SELECT campo1,campo2 FROM usuario WHERE rut =?");//aqui lo adecuado seria poner los campos que nececitas
    $stmt->bind_param("i",$Codigo);//aqui estoy suponiendo que el valor de la variable codigo es un entero, por eso pongo i entre comillas, si fuera lo comtrario osea un string tienes que poner una s
    $stmt->execute();
    $stmt->bind_result($campo1,$campo2);//con bind_result traeras los campos espesificados en el select , nota:tienen que ser en el mismo orden
        $row->fetch()) {
            printf("%s %s\n", $campo1, $campo2);
        }
    
        /* cerrar la sentencia */
        $stmt->close();
    }
    /* cerrar la conexión */
    $conn->close();
    
        
    answered by 30.10.2018 в 15:32