PipBoy2000 PipBoy2000 - 3 months ago 8
MySQL Question

How to use PHP variables in MySQL queries with WHILE fetched rows?

I have successfully done the php script that connect to my database and return desired data. But i need to extend this script to insert a variable that will show the price with some calculations (tax,no-tax,margin etc.).

This script show me only price value of the first database row 0.00 in all fetched rows and its not correct - for the first database row is ok because product have 0.0000 price, but the other rows are filled with correct values. It seems like the while loop dont like my $styledprice variable . I can't figure how to show correct field values in all lines. Any ideas much apppreciated? I'm a PHP beginner!

$pricequery = "SELECT rrp FROM my_products";
$b2bprice = mysql_query($pricequery);
$rrps = mysql_fetch_array($b2bprice);
$price = $rrps['rrp'];
$styledprice = number_format($price, 2, '.', '');

$query = mysql_query("
SELECT
CONCAT(' <td> ',p.id,' </td><td> ',p.manufacturer,' </td><td> ',p.reference,' </td><td> ',p.name,' </td><td> ',p.quantity,' <td> ','".$styledprice."',' </td> ') AS row
FROM my_products p
");

echo "
<table>
<tr>
<td><h5>ID</h5></td>
<td><h5>Manufacturer</h5></td>
<td><h5>PN</h5></td>
<td><h5>Name</h5></td>
<td><h5>Quantity</h5></td>
<td><h5>Price</h5></td>
</tr>";

while($row=mysql_fetch_array($query))
{
echo "<tr>".$row['row']."</tr>";
}

echo "
</table>";


Yes i know about mysql_ functions that are deprecated.

Answer

Something like this should work better. It seperates the resultset from the database and the output via HTML.

// Get the Result Set
$result =  mysql_query("SELECT p.id, p.manufacturer, p.reference, p.name, p.quantity FROM my_products p");

// Convert the rows and columns from the Result Set to a PHP Array
$data = array(); // empty array
while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row;
}

// Now you have access any row or column
echo "<table>";
foreach($data as $row){

    // prepare the data
    $formatttedQuantity = number_format($row['quantity'], 2, '.', '');

    // show each Table Row

    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['manufacturer'] . "</td>";
    echo "<td>" . $row['reference'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $formatttedQuantity . "</td>";
    echo "</tr>";
}
echo "</table>";
Comments