Difficulty in listing an invoice and products using PHP and MySQL

0

I'm having trouble on this page right below. My difficulty is in displaying the products of a particular invoice. Because in statment SELECT * FROM produtos WHERE = ? does not return anything! But when I put the number physically ( SELECT * FROM produtos WHERE = 4519 ) it displays normally!

Here is the code:

<code>
    include 'banco.php';
    $nota = $_GET['nota'];
    $pdoo = Banco::conectar();
    $sqll = "SELECT * FROM produtos where numnota = ?";
    $qq = $pdoo->prepare($sqll);
    $qq->execute(array($nota));
    $dataa = $qq->fetch(PDO::FETCH_ASSOC);
    print_r($dataa);

    foreach ($pdoo->query($sqll)as $row) {  
        echo '<tr>';
        echo '<td>'.$row['descricao'].'</td>';
        echo '<td>'.$row['unidade'].'</td>';
        echo '<td>'.number_format($row['qtde'],"2",",",".").'</td>';
        echo '<td>R$ '.number_format($row['valunit'],"2",",",".").'</td>';
        echo '<td>R$ '.number_format($row['desconto'],"2",",",".").'</td>';
        echo '<td>R$ '.number_format($row['total'],"2",",",".").'</td>';
        echo '</tr>';
    }
    Banco::desconectar();
</code>
    
asked by anonymous 21.04.2018 / 21:19

1 answer

1

The problem is occurring on the following line:

foreach ($pdoo->query($sqll)as $row) {

Simply replace it with:

foreach ($dataa as $row) {

I looked here and have another problem. You want all the products of a particular note. So instead of using fetch:

$dataa = $qq->fetch(PDO::FETCH_ASSOC);

Use fetchAll to fetch all rows:

$dataa = $qq->fetchAll(PDO::FETCH_ASSOC);

Why the problem is occurring

When executing the query method it just executes your select. It does not take into account the replacement of parameters. So it is recommended to use the execute. Here's a brief description of both:

query executes a standard SQL statement and requires you to properly escape all data to avoid injection.

execute executes a prepared statement that allows you to link parameters to avoid the need to escape them.

Your corrected solution would look like this:

include 'banco.php';
$nota = $_GET['nota'];
$pdoo = Banco::conectar();
$sqll = "SELECT * FROM produtos where numnota = ?";
$qq = $pdoo->prepare($sqll);
$qq->execute(array($nota));
$dataa = $qq->fetchAll(PDO::FETCH_ASSOC);
print_r($dataa);

foreach ($dataa as $row) {  
    echo '<tr>';
    echo '<td>'.$row['descricao'].'</td>';
    echo '<td>'.$row['unidade'].'</td>';
    echo '<td>'.number_format($row['qtde'],"2",",",".").'</td>';
    echo '<td>R$ '.number_format($row['valunit'],"2",",",".").'</td>';
    echo '<td>R$ '.number_format($row['desconto'],"2",",",".").'</td>';
    echo '<td>R$ '.number_format($row['total'],"2",",",".").'</td>';
    echo '</tr>';
}
Banco::desconectar();
    
22.04.2018 / 20:06