1

I know it must be something very silly I'm missing here. I have a table and all calculations are working great. I'm stuck here:

After while loop I can echo ttl_sold and all other information everything except "balance".

in while loop these are fine and I get results:

$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql); ?>

<?php
$sum = $sum + $rows['total'];
$ttlsold = $ttlsold + $rows['quantity'];
?>


<?php

$sum = 0;
$ttlsold = 0;

while($rows=mysql_fetch_array($result)){

ttl_sold is 12 and when I echo "balance" I get -12. I did try to include this within the loop and outside, but still no luck!

<?php
$balance = "SELECT stock FROM tbl_name WHERE id = 1";
$balance = $balance - $ttl_sold;
?>

<table width="1000" border="1" cellspacing="0" cellpadding="3">
<tr>
<td width="100"><?php echo $balance; ?></td>

Any idea? Thanks!

StillTrying
  • 23
  • 1
  • 7
  • $balance is the SQL statement as a string variable.... you're not executing the SQL query or getting the result... suggest you look at the PHP manual for the basics of database access.... and learn PDO (http://www.php.net/manual/en/book.pdo.php) rather than the deprecated MySQL that most people will suggest – Mark Baker Feb 17 '13 at 11:06
  • Please show us the entire relevant code, including the part where you execute the query and the loop you speak of. – Tim Post Feb 17 '13 at 11:11
  • Thanks. Added the other parts. – StillTrying Feb 17 '13 at 11:21

2 Answers2

2

try this,

$query = "SELECT stock FROM tbl_name WHERE id = 1";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
    $balance = $row['stock'];
    $balance = $balance - $ttl_sold;
}

The article below talks about SQL Injection but it introduces how to use new PHP Extensions such as PDO and MySQLi.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
1

You are doing something like this:

$balance = "SELECT stock FROM tbl_name WHERE id = 1" - 12;
// PHP makes:
$balance = (int) "SELECT stock FROM tbl_name WHERE id = 1" - 12;
// And moreover:
$balance = 0 - 12;
$balance = -12;

You have to execute this query first, for MySQL you can use PDO or MySQLi.

pamil
  • 980
  • 2
  • 10
  • 20