tags:

views:

47

answers:

2

OK,

In this query I am displaying the sales for a particular person, matching the passport number from the current form I am working on.

What I want to do however, is to sum the total sales and display it, excluding records which have been marked as paid.

I am having trouble because "paid" does not existent in the current form I am working on as a variable, nor the table it relates to.

I can´t use row['paid'] as I need to do this query outside of the while loop.

What should I do in this situation?

$sqlstr = mysql_query(
        "SELECT * FROM sales where passport = ".
        "'{$therecord['passport']}'");
if (mysql_numrows($sqlstr) != 0) {
    echo "<b>Sales for {$therecord['firstname']} ".
            "{$therecord['lastname']}</b><br />";
    echo "<table><tr>";
    echo '<tr><th align="left">Name</th><th align="left">Quantity</th>".
            "<th align="left">Cost</th></tr>';
    while ($row = mysql_fetch_array($sqlstr)) {
        echo "<td>{$row['product']}</td>";
        echo "<td>{$row['quantity']}</td>";
        echo "<td>{$row['cost']}</td>";
        echo "</tr>";
    }
}

echo "</table>";
$sqltotal = mysql_query(
        "SELECT SUM(cost) as total FROM sales where passport = ".
        "'{$therecord['passport']} AND {$therecord['paid']} <> 1'");
$row = mysql_fetch_array($sqltotal);
echo "<br /><b>Total Owing: {$row['total']}</b>";
+1  A: 

you've misplaced simple quote in :

"'{$therecord['passport']} AND {$therecord['paid']} <> 1'"

it must be :

"'{$therecord['passport']}' AND {$therecord['paid']} <> 1"
M42
Hmm, I still get an error Undefined index: paid when trying that solution.
Jacob
what's the contents of $therecord['paid'] ?
M42
I can´t even access it, as it gives the undefined index error. That is kind of my problem, $therecord has just results from a table which does not have a paid field. So I need to access it in the query I make from the sales table in my query above.
Jacob
May be your field is paid instead of $therecord['paid'] so you'll have :"'{$therecord['passport']}' AND paid <> 1"
M42
Hmm, that seems to be it, except now nothing is output for the total at all.
Jacob
Are you sure that you have data in your DB. Try SELECT cost FROM ... instead of SELECT SUM(cost) ...
M42
Definitly data in the DB...the individual sales and costs are showing, just not the totals.
Jacob
+1  A: 

You could either create a MySQL view, of look at SQL joins. I'm not sure on your database structure, but you should have a SQL query like this:

SELECT SUM(sales.cost) AS total
FROM sales, table2
WHERE sales.passport = '$passport_id'
AND sales.passport = table2.passport
AND table2.paid = '1'

Not sure as that was wrote off-hand. Again, it'd be better if we knew the structure of your tables.

Martin Bean