2

I have this sql query:

SELECT * 
FROM products p, products_description pd, products_to_categories c left 
     join  products_sex ps on (c.products_id = ps.products_id), 
     categories cc 
WHERE p.products_id = pd.products_id 
      and p.products_id = c.products_id 
      and cc.categories_id = c.categories_id 
      and p.products_status = 1 
      and p.products_price >= 15.8333333333 
      and p.products_price <= 40 
      and p.products_quantity > 0 
      and (ps.products_sex = "U" or ps.products_sex is null) 
      and (c.categories_id = 77 or cc.parent_id = 77) 
ORDER BY products_sort_order, p.products_date_added desc, pd.products_name ASC 
LIMIT 0, 40

If I execute it at MySQL client (command line or Navicat), I get this result:

products_id  |  dodavatelia_id  ...
2153         |  67              ...

But if I get products by PHP script (with mysql_query and mysql_fetch_assoc), I get:

array ( 
    'products_id' => NULL,  
    'dodavatelia_id' => '67', 
    ...
);

Why am I getting the products_id NULL?

1 Answer 1

2

This might be because you are joining multiple tables that contains column with the same name, here products_id so you retrieve the value of the last column with this name that might be NULL.

You should put an alias for the column you want to retrieve :

SELECT p.products_id AS pPropId, p.* FROM products p, ...

Then in your PHP result you can access your column like this:

$result['pPropId']

More info on the SQL Alias functionality here.

EDIT: Why does it work in the command line and not here?

The SQL query works fine and will return each column of name products_id. The issue is that you use mysql_fetch_assoc() that returns an associative array based on your result. And you can't have multiple values for the same key in the array.

So what it might do internally is set $result['products_id'] = p.products_id but then it does the same for the next column with the same name erasing the previous value. You could use mysql_fetch_row() which does not have this issue.

A good practice is to list the columns you really want to retrieve in your SELECT and not just SELECT *. Then it becomes logical that two columns with the same name need different aliases.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this was it. But I don't understand, why it works in mysql command line and in PHP doesn't.
@yetty > Because the SQL query works fine. Check my updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.