How to update this code to PDO

-1

Hello, I am trying to update a table in MySQL with jQuery , with queries to PDO . Here I have the code that I do not know how to update:

while($registro2 = mysql_fetch_array($registro)){
        $tabla = $tabla.'<tr>
                            <td>'.$registro2['nomb_prod'].'</td>
                            <td>'.$registro2['tipo_prod'].'</td>
                            <td>S/. '.$registro2['precio_unit'].'</td>
                            <td>S/. '.$registro2['precio_dist'].'</td>
                            <td>'.fechaNormal($registro2['fecha_reg']).'</td>
                            <td><a href="javascript:editarProducto('.$registro2['id_prod'].');" class="glyphicon glyphicon-edit"></a> <a href="javascript:eliminarProducto('.$registro2['id_prod'].');" class="glyphicon glyphicon-remove-circle"></a></td>
                          </tr>';       
    }

In my case it only occurs to me to do a fetchAll() and a forEach but I do not know if it would be fine.

    
asked by Perl 15.09.2016 в 15:02
source

1 answer

0

A little information is missing from the question. However, in order to help you, I can give you the following tips and partly answer your question:

1. Do not use the mysql drivers

The "mysql" drivers are disabled in the latest versions of PHP and it is likely that if you upload your code to a shared server, you can not use it because of this (in addition to having its functions declared obsolete). ). I know that the question is precisely how to re-use the code to PDO, but I do not want to stop mentioning this in case someone else reads it.

2. Doing a while to read records is a fairly common practice

Doing a while is a fairly common practice when reading information from a database, which is why the logic you present and sample in the code is fine.

3. You can use PDO or MySQLi

Not only can you use PDO, you can also use MySQLi which is quite similar to the MySQL driver and you may not have to change much if you opt for the latter.

4. Work object oriented

The current code uses the "mysql" driver and is not object oriented. As a tip, I recommend you always use the drivers and work them oriented to objects. Obviously, this will depend on the context you're in.

With regard to the specific question, venturing without having seen the rest of the code, could be something similar to the following (assuming that somewhere else you created the connection and everything necessary):

$sentencia = $con->prepare('SELECT * FROM nombre_tabla WHERE id = :id');
$sentencia->execute(array('id'=>$valor_id));

while($registro2 = $sentencia->fetch()){
  //código para mostrar $registro2 y su contenido...    
}

I leave a link in which there is just a comparison between these three (mysql, PDO and mysqli) and shows how to use each one. I hope it serves to clarify doubts.

link

    
answered by 15.09.2016 в 16:49