mysql_fetch_assoc函数替换

时间:2013-08-17 16:04:25

标签: php mysql foreach

在我的PHP代码中我有2个循环并且它们正常运行,除了1如果我不能替换以下函数的语句。

(1)虽然此代码很好并且在第一个循环中运行

if(isset($_GET['Filter']) && !empty($_GET['Filter'])){
    $query = "SELECT * FROM Apartment WHERE ";
    foreach( $_GET['Filter'] as $filter ){
        $query .= "$filter='y' AND ";
    }
    $query = substr($query, 0, -5);
}

while($data = mysql_fetch_array( $result )) {
    //echo $data
}

(2)另一个给出了sql错误

if(isset($_GET['Filter']) && !empty($_GET['Filter'])){
    $sql = mysql_query("SELECT * FROM Apartment WHERE" );
    foreach( $_GET['Filter'] as $filter ){
        $sql .=("$filter='y' ORDER BY RegularPrice ASC LIMIT 1 AND ");
    }
    $sql = substr($sql, 0, -5);
}

while($row = mysql_fetch_assoc($sql)) {
    //echo $row
}

任何人都可以帮助我在(2)秒中找到最终的语法错误,如果我发布的是哪个语句?

2 个答案:

答案 0 :(得分:1)

摆脱mysql_query(

$sql = mysql_query("SELECT * FROM Apartment WHERE" );

$sql = "SELECT * FROM Apartment WHERE";

因为它位于顶部...这是一个执行查询的函数 - 我很确定你不想这样做。

顺便说一句,在你的示例代码中 - 既没有真正正确地执行查询 - 所以fetch_assoc调用也不起作用(我假设你只是将它们清理掉了。)

干杯

答案 1 :(得分:1)

对于第二个查询,您将部分mysql_query()分配给变量$sql,然后将字符串连接到它。我认为这是一个错误,您只想将字符串SELECT * FROM Apartment WHERE分配给变量$sql

另外,请注意您正在连接的字符串:

$sql = mysql_query("SELECT * FROM Apartment WHERE" );
foreach( $_GET['Filter'] as $filter ){
    $sql .=("$filter='y' ORDER BY RegularPrice ASC LIMIT 1 AND ");
}

这会产生类似的东西:

SELECT * FROM Apartment WHERE filter1='y' ORDER BY RegularPrice ASC LIMIT 1 AND filter2='y' ORDER BY RegularPrice ASC LIMIT 1 AND filter3='y' ORDER BY RegularPrice ASC LIMIT 1 AND

这是一个无效的SQL查询。

您想要尝试的是:

$sql = "SELECT * FROM Apartment WHERE ";
foreach( $_GET['Filter'] as $filter ){
    $sql .= "$filter='y' AND ";
}
$sql = substr($query, 0, -5); // Remove the last ' AND '
$sql .= " ORDER BY RegularPrice ASC LIMIT 1";

$result = mysql_query ($sql);