user1491318
user1491318

Reputation: 29

Echo variable which has same name in php join

I have a mysql join which is pulling from two tables name product & cart and they're both being pulled from a variable $row_checkout

If i have to echo a certain field, i can normally go $row_checkout['cartid'] and that works fine.

However, i have a coloumn in each table which is called the same 'Status'.

How do i echo from one of the tables? I thought something like $row_checkout['cart.status'] might work but it doesnt appear to?

My database code is as follows:

$colname_checkout = "-1";
if (isset($row_booking['sessionid'])) {
  $colname_checkout = (get_magic_quotes_gpc()) ? $row_booking['sessionid'] : addslashes($row_booking['sessionid']);
}
mysql_select_db($database_main, $main);
$query_checkout = sprintf("SELECT * FROM cart, productdatabase WHERE cart.productid = productdatabase.productid AND cart.status != 1 AND cart.status != 0 AND cart.sessionid = '%s' ORDER BY `name` ASC", $colname_checkout);
$checkout = mysql_query($query_checkout, $main) or die(mysql_error());
$row_checkout = mysql_fetch_assoc($checkout);
$totalRows_checkout = mysql_num_rows($checkout);

Upvotes: 0

Views: 935

Answers (2)

Ivanka Todorova
Ivanka Todorova

Reputation: 10219

Use alias.

Refernce : http://www.tutorialspoint.com/sql/sql-alias-syntax.htm

 $query_checkout = 
 sprintf("SELECT *,**cart.status AS cart_status, productdatabase.status as
 pdb_status** FROM  cart, productdatabase WHERE
 cart.productid = productdatabase.productid AND
 cart.status != 1 AND cart.status != 0 
 AND cart.sessionid = '%s' ORDER BY `name` ASC", $colname_checkout);

Upvotes: 0

Nicole Stutz
Nicole Stutz

Reputation: 516

You can use alias to change a tables field name, to a name that you want.

the cart.status filter, you could make simpler, simpler by asking > 1

SELECT c.status as car_status, pro.status as pro_status 
FROM cart as c, productdatabase as pro
WHERE c.productid = pro.productid AND c.status >1 AND c.sessionid = '%s' 
ORDER BY `name` ASC", $colname_checkout

Seeing what you get, it will display an associative array with all names and values, that you can use to address the data

while ($row_checkout = mysql_fetch_assoc($checkout)) {
    print_r($row_checkout);
}

or specific the fields:

while ($row_checkout = mysql_fetch_assoc($checkout)) {
    echo $row_checkout["car_status"];
    echo $row_checkout["pro_status"];
}

another comment, the mysql function is not recommended anymore. You could use MySQLi or PDO_MySQL. They are both object oriented and may need a little more time to learn.

Upvotes: 2

Related Questions