在PHP脚本MySQL查询返回NULL列

时间:2013-02-09 09:35:46

标签: php mysql null

我有这个SQL查询:

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

如果我在MySQL客户端(命令行或Navicat)执行它,我得到这个结果:

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

但如果我通过PHP脚本(使用mysql_query和mysql_fetch_assoc)获得产品,我会得到:

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

为什么我将products_id设为NULL?

1 个答案:

答案 0 :(得分:2)

这可能是因为您要连接多个包含具有相同名称的列的表,此处为products_id,因此您可以使用此名称NULL检索最后一列的值。

您应该为要检索的列添加别名:

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

然后在您的PHP结果中,您可以像这样访问您的列:

$result['pPropId']

有关SQL别名功能的更多信息here

编辑:为什么它在命令行中工作而不在这里?

SQL查询工作正常,将返回名称为products_id每个列。问题是您使用mysql_fetch_assoc()根据结果返回关联数组。并且您不能为数组中的相同键设置多个值。

那么内部可能做的是设置$result['products_id'] = p.products_id,但是对于具有相同名称的下一列删除前一个值它会做同样的事情。您可以使用没有此问题的mysql_fetch_row()

一个好的做法是在SELECT中列出您真正想要检索的列而不仅仅是SELECT *。然后,具有相同名称的两列需要不同的别名,这是合乎逻辑的。