Link to home
Start Free TrialLog in
Avatar of easttncs
easttncs

asked on

Refering to query fields by their column names when outputting data.

When displaying the output of a query. I would like to use the actual names of the fields for readability instead of $row[0] etc. I have been unable to do this. I have the following quiery.

$sql1 =      "SELECT COUNT(available_qty) AS BOP_Stock FROM product_snapshot WHERE thumbnail_ID = " . $_POST['thumbnail'] . " AND snapshot_date >= '" . $_POST['snapshot_date'] . "' AND snapshot_date < '" . $end_date . "'";

And the following display line....

<?php while ($row = mysql_fetch_row($getBOP_Stock)) { echo "$row[BOP_Stock]"; }?>

I have tried several variations including the quotes and excluding the quotes to no avail.

What am I missing.





ASKER CERTIFIED SOLUTION
Avatar of Raynard7
Raynard7

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KarlPurkhardt
KarlPurkhardt

Raynard7 is spot on. Incidentally though, when accessing the associative array, do it like this, with the quotes:

$row['BOP_Stock'];
You can use either mysql_fetch_assoc() which will get return the names of the columns, or mysql_fetch_array() which will return the array with both the column and the numbers.

Nevermind Karl, your example is correct with your echo statement (echo "$row[BOP_Stock]";). If you are echoing your array values within a string, you can't put the index in quotes. If you took it out of the quotes, then you would need your index in quotes so either of the two lines below would echo correctly:

echo "$row[BOP_Stock]";
echo $row['BOP_Stock'];

Other options would include using mysql_fetch_object() where you could reference the variable like so:

echo "$row->BOP_Stock";

or you could extract all the variable indexes and use

extract($row);
echo $BOP_Stock;