How to identify a column in mysql when I have 2 with the same name

advertisements

I'm using this PHP code to get my sql query which joins 2 tables ... both table have the same "size" field, but the results is not the same in both... code:

mysql_query("SELECT * FROM cart INNER JOIN tbl_product ON tbl_product.product_id =
cart.product_id WHERE .......) or die(mysql_error());

The result of this query shows me

Cart_id, member_id, product_id, size, .... and a second size

1 of the size comes the cart table and 1 from the product table..

then I try to retrieve my data

while($data2 = mysql_fetch_array( $data))
{
    $size=  $data2['size'];

But I get the second size in my result and I need the first one.. I need the cart.size ... how can I do this ?


Name the columns explicitly in your SELECT statement, and assign ALIASes to the columns with identical names:

SELECT cart.id_col, cart.size AS CartSize, ttbl_product.size AS ProductSize
  FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id
  WHERE .......

then extract the value for ProductSize from the results.

If you don't need the cart size, you can eliminate it from the list of columns return and leave out the ALIAS, as you'll only have a single Size column in the results:

SELECT cart.id_col, ttbl_product.size
  FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id
  WHERE .......

In general, it's a good idea to explicitly name the columns you want in your SELECT statement as it makes it clearer what you're getting back, it will fail sooner if you are trying to get a column that's not there (when the SELECT executes, not when you try to retrieve the column value from the result set), and can lead to better performance if you're only interested in a small-ish subset of the available columns.