Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Joined Tables, same field name question

8:26 am on Jul 15, 2011 (gmt 0)

New User

5+ Year Member

joined:July 14, 2011
posts: 19
votes: 0


probably another really basic question.

But I have a select across 2 joined tables and they both have a field STATUS, that has a different meaning in each table.

I am used to using this kind of function to access query results:

$rows = mysql_fetch_assoc($result);
$status1 = $rows['status'];

Except, the query array contains these 2 values of STATUS - how does one go about specifiying which one is which?

Thanks for your help.

9:08 am on July 15, 2011 (gmt 0)

Preferred Member

10+ Year Member

joined:Jan 4, 2005
votes: 0

select table1.status as table1_status, table2.status as table2_status

Does that help?

Status isn't the best name for a table field. I believe it is a reserved word in mysql. Try something like user_status next time or order_status. then it is already defined to you as well. You could even change the row names now and avoid the query I wrote uptop altogether.
4:15 pm on July 15, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
votes: 0

You can use the as keyword to assign them to a variable as mentioned, or something not many people use.

mysql_fetch_array (not assoc) returns two arrays - an associative and a list array. So you can also do

echo $row[0]; // id - remember list arrays start index at 0
echo $row[5]; first status
echo $row[11]; second status

This is extremely useful when you begin to optimize your code for expandability. A very basic example:

$table = 'mytable';
$fields = get_table_names($table); // A function you'd write
$len = count($fields);

$q = "select * from $table where id=1234";
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
for ($i=0;$i<$len;$i++) {
echo "<p>Field: " . $fields[$i] . " Value: " . $row[$i] . "</p>\n";

Any table, any time . . . change the database by adding or rearranging fields, it still works. :-)

How you'd do that in a join? Also a very **basic** example,

$table = 'mytable';
$jointable = 'myjoin';
$fields = get_table_names($table);
$joinfields = get_table_names($jointable);
$len = count($fields)
$total_len = $len + count($joinfields);

$q = "select $table.*,$jointable.* from $table,$jointable where $table.$joinfield=$jointable.$joinfield and $table.id=1234";
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
for ($i=0;$i<$total_len;$i++) {
if ($i<$len) { echo "<p>Field: " . $fields[$i]; }
else { echo "<p>Join Field: " . $joinfields[$i-$len]; }
echo " Value: " . $row[$i] . "</p>\n";

You can also use array_keys to get field names, but sometimes you need them before actually running a query (table heads.)