我有这段PHP代码:
$dcs = mysql_query("SELECT `locations.l_name`, `locations.location_id`
FROM `locations`, `cabinet`
WHERE `locations.location_id` = `cabinet.datacentre_id`
GROUP BY `locations.location_id`
ORDER BY `locations.l_name`");
while ($row = mysql_fetch_array($dcs)) {
echo '<option value="' .$row['location_id']. '">' .htmlspecialchars($row['l_name']). '</option>'; }
但是当我运行它时,我收到了这个错误:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
我很确定这是数据库的问题,而不是代码..任何想法可能是什么问题?或者我需要注意什么?
答案 0 :(得分:3)
您的SELECT
查询不正确。您将表名和列名包装为一个,导致服务器找不到列名。它们应该单独包装。
SELECT `locations`.`l_name`,
`locations`.`location_id`
FROM `locations`, `cabinet`
WHERE `locations`.`location_id` = `cabinet`.`datacentre_id`
GROUP BY `locations`.`location_id`
ORDER BY `locations`.`l_name`
由于它们不是mysql中保留的keyowrds,backticks
是可选的。
SELECT locations.l_name,
locations.location_id
FROM locations, cabinet
WHERE locations.location_id = cabinet.datacentre_id
GROUP BY locations.location_id
ORDER BY locations.l_name
还有一件事,请使用更新的连接语法。
SELECT locations.l_name,
locations.location_id
FROM locations
INNER JOIN cabinet
ON locations.location_id = cabinet.datacentre_id
GROUP BY locations.location_id
ORDER BY locations.l_name
答案 1 :(得分:0)
对我来说工作正常...虽然注意到这个PHP方法已被“弃用”了!...
<?php
include('path/to/connection/stateme.nts');
$query = "
SELECT DISTINCT l.l_name
, l.location_id
FROM locations l
JOIN cabinet c
ON c.datacentre_id = l.location_id
ORDER
BY l.l_name;
";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo '<option value="' .$row['location_id']. '">' .htmlspecialchars($row['l_name']). '</option>';
}
?>