0

我有这段 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

我很确定这是数据库的问题,而不是代码的问题。任何想法可能是什么问题?或者我需要注意什么?

4

2 回答 2

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中的保留关键字,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
于 2013-03-18T09:18:28.107 回答
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>';
 }
 ?>
于 2013-03-18T09:30:00.687 回答