0

我的代码有问题。mysql_fetch_array 输出重复相同的值。这是我的代码:

$sql= "SELECT client.resID AS resID, client.resName AS resName, menu.id AS mid, menu.name AS mname, facilities.name AS fname, facilities.id AS fid FROM client INNER JOIN menu ON client.resID = menu.resID INNER JOIN facilities ON client.resID = facilities.resID WHERE client.resID =".$_GET["resID"];
$rs = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());



while ($f = mysql_fetch_array($rs)) { // loop as long as there are more results
    $names[] = $f['mname'];  // push to the array

print_r($names)

}

假设一家餐馆有米饭和土豆。print_r($names) 正在返回:

Array ( [0] => rice [1] => potato [2] => rice [3] => potato [4] => rice [5] => potato [6] => rice [7] => potato [8] => rice [9] => potato ) 

我该如何解决这个问题?非常感谢您的帮助:D

4

3 回答 3

1

使用分组

$sql= "SELECT client.resID AS resID, client.resName AS resName, menu.id AS mid, 
       menu.name AS mname, facilities.name AS fname, facilities.id AS fid 
    FROM client 
    INNER JOIN menu ON client.resID = menu.resID 
    INNER JOIN facilities ON client.resID = facilities.resID 
    WHERE client.resID =".$_GET["resID"]." 
    group by mname ";
于 2012-12-08T06:17:42.510 回答
1

您的查询

SELECT client.resID AS resID, client.resName AS resName,
       menu.id AS mid, menu.name AS mname,
       facilities.name AS fname, facilities.id AS fid 
FROM client
INNER JOIN menu ON client.resID = menu.resID
INNER JOIN facilities ON client.resID = facilities.resID
WHERE client.resID =".$_GET["resID"]

返回与其他两个表匹配的次数一样多的“大米”。由于您要连接由 设置的列WHERE,因此您的查询实际上是三个连接表的笛卡尔积(在过滤后resID)。

前任。:

john rice fac1
john meat fac1
john rice fac2
john meat fac2
...

也许您想进行三个单独的查询,每个表一个

SELECT mid, mname FROM menu WHERE resID = $resID

或者,也许您想加入其他列(例如,在所有三个表中唯一的列)?

SELECT ...
FROM client
INNER JOIN menu ON client.resID = menu.id
INNER JOIN facilities ON client.resID = facilities.id

另请注意,在查询字符串中包含未转义的 get 参数是危险的,即使您期望数字也是如此。使用mysqli 准备好的语句或(至少)mysql_real_escape_string

于 2012-12-08T06:35:18.663 回答
0

正如 Man Programmer 所说,您可以使用Group By

$sql= "SELECT client.resID AS resID, client.resName AS resName, menu.id AS mid, menu.name AS mname, facilities.name AS fname, facilities.id AS fid FROM client INNER JOIN menu ON client.resID = menu.resID INNER JOIN facilities ON client.resID = facilities.resID WHERE client.resID =".$_GET["resID"]." group by mname ";

或者,如果您不想要 Group By,您可以使用这种代码。

 $items = array();
    $sql= "SELECT client.resID AS resID, client.resName AS resName, menu.id AS mid, menu.name AS mname, facilities.name AS fname, facilities.id AS fid FROM client INNER JOIN menu ON client.resID = menu.resID INNER JOIN facilities ON client.resID = facilities.resID WHERE client.resID =".$_GET["resID"];
    $q = mysql_query ( $sql ) or die( mysql_error() );
    while( $row = mysql_fetch_assoc( $q ) ) {
     if( !in_array( $row['mname'],$items ) ) {
        $items[] = $row['mname'];
     }
    }

print_r( $items )

如果它检测到它已经具有那种值,它将跳过在数组中存储值。

于 2012-12-08T06:27:58.610 回答