TheWebWeeb TheWebWeeb - 13 days ago 10
PHP Question

Need someone to correct my mysql query for table creation

I want to create a table as that I can have in the one variable (going to send it to js later on) and then display it. But result of my echo is only table head ('Produkty', 'Ilość', 'Cena'). Can you show me where I made mistakes or correct me?

<?php

header('Access-Control-Allow-Origin: *');
include "database.php";


$dane = array();
$tabela='<table class="table table-striped">
<thead>
<tr>
<th>Produkt</th>
<th>Ilość</th>
<th>Cena</th>
</tr>
</thead>
<tbody>';
$dane=array();

$sql_main="SELECT Products.`Name`,Orders_NEW.`Amount`,((Products.`Price`)*(Orders_NEW.`Amount`)) as 'PRICE' FROM `Orders_NEW` inner join `Products` on Orders_NEW.`Product`=Products.`ID` AND `Order_ID`=669";

$dane = $db->query($sql_main);

foreach($dane as $row)
{
$tabela.="<tr><td>".$row['Name']."</td><td>".$row['Amount']."</td><td>".$row['Price']."</td></tr>";
}

$sql_second="SELECT SUM((Products.`Price`)*(Orders_NEW.`Amount`)) as 'SUMA' FROM `Orders_NEW` inner join `Products` on Orders_NEW.`Product`=Products.`ID` AND `Order_ID`=669";

$dane_second= array();

$dane_second= $db -> query($sql_second);

foreach($dane_second as $row)
{

$tabela.='<thead>
<tr>
<th>Łącznie</th>
<th></th>

<th>'.$row["SUMA"].'</th>
</tr>
</thead>
</table>';
}

echo($tabela);



?>


Edited: Changed foreach into while($row = $dane->fetch_assoc())
Now my result is:

Produkt Ilość Cena

Łącznie

seems like variables like $row['Name'] etc is the problem here

Answer

I'm not sure if you have some sort of custom class with database.php, but if $db just contains mysqli object then you need to do the following:

$dane = $db->query($sql_main);

while($row = $dane->fetch_assoc()) {
    $tabela.="<tr><td>".$row['Name']."</td><td>".$row['Amount']."</td><td>".$row['Price']."</td></tr>";
}

Same goes for the second query (this assumes your SQL is correct and returning results by the way).