PHP MySQL - 多次获取数组循环

时间:2012-12-08 06:14:55

标签: php mysql

我的代码出了问题。 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

3 个答案:

答案 0 :(得分: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 ";

答案 1 :(得分: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"]

与其他两个表匹配的次数一样多次返回“rice”的出现次数。由于您要加入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 prepared statements或(至少)mysql_real_escape_string

答案 2 :(得分: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 )

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