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?
This might be because you are joining multiple tables that contains column with the same name, here
products_idso you retrieve the value of the last column with this name that might beNULL.You should put an alias for the column you want to retrieve :
Then in your PHP result you can access your column like this:
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 usemysql_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_idbut 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.