Conversion of SESSION MySQL to SESSION in PDO

1

How do I convert this SESSION below MySql to PDO.

<?php
    if(count($_SESSION['carrinho']) == 0){
        echo '<tr><td colspan="5">Não há produto no carrinho</td></tr>';
    }else{
        require("conexao.php");
    $total = 0;
        foreach($_SESSION['carrinho'] as $codigo => $qtd){
        $sql   = "SELECT * FROM produto WHERE codigo= '$codigo'";
        $qr    = mysql_query($sql) or die(mysql_error());
        $ln    = mysql_fetch_assoc($qr);

        $titulo  = $ln['titulo'];
        $preco = number_format($ln['preco'],2,",",".");
        $sub   = number_format($ln['preco'] * $qtd,2,",",".");

        $total += $ln['preco'] * $qtd;

        echo '<tr style="font-size:11px; font-weight:bold; color:#000;">       
                  <td  align="left">'.$titulo.'</td>
                  <td align="center"><input type="text" size="1" name="prod['.$codigo.']" value="'.$qtd.'" /></td>
                  <td align="center">R$ '.$preco.'</td>
                  <td align="center">R$ '.$sub.'</td>
                  <td align="center">
                    <a href="?acao=del&codigo='.$codigo.'">
                        <img width="25" src="img/del.png" title="Remover '.$titulo.'"/>
                    </a>
                  </td>
              </tr>';
        }
        $total = number_format($total,2,",",".");
          echo '<tr>
                    <td align="right" style="font-size:16px; font-weight:bold; color:#990000;" colspan="3">Total</td>
                    <td align="left" style="font-size:16px; font-weight:bold; color:#000;" colspan="4">R$ '.$total.'</td>
                </tr>';
        }
?>

Because she's returning this error message:

Deprecated: mysql_query (): The mysql extension is deprecated and will be removed in the future: use mysql or PDO

I think it's because this two lines are with mysql_query ():

$qr    = mysql_query($sql) or die(mysql_error());
$ln    = mysql_fetch_assoc($qr);

Can friends help me convert these two lines to the PDO?

    
asked by anonymous 15.07.2018 / 15:08

1 answer

2

First you create the connection to the database:

$dbname="nome_do_banco_de_dados";
$dbuser="nome_do_usuario_do_banco";
$dbpassword="senha_do_usuario";

try{
    $conn=new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpassword,array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET NAMES utf8"));
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $error){
    return 'Erro: '.$error->getMessage();
}

Then execute the querys using PDO :

$sql="SELECT * FROM produto WHERE codigo= '$codigo'";
$exec=$conn->prepare($sql);
$exec->execute();
$results=$exec->fetchAll(PDO::FETCH_ASSOC);
  

CRUD article with PDO - DevMidia

     

Article about CRUD with PDO - GigaSystems

    
15.07.2018 / 17:40