for循环中的mysql_query给出了mysql_fetch_assoc相关的错误/警告

时间:2012-06-26 18:19:32

标签: php mysql database

我试图获取特定用户回答或询问的问题的id,而不是尝试使用这些id并获取id与第一个查询中检索到的id不同的问题。试图实现此目标得到一个mysql_fetch_assoc()相关的错误/警告,结果我的程序崩溃了。

以下是我的DB_Functions.php文件中的代码,我在数据库上执行查询。

public function getQuestions($username){
$result = mysql_query("SELECT question_id FROM answered WHERE asked_by =  '$username' OR answered_by =  '$username'");
if($result){
$data = array();
    while($row = mysql_fetch_assoc($result)) {
        $data[] = array(
        $r=$row["question_id"]);}
        for($i=0; $i<sizeof($data); $i++){
            $result2 = mysql_query("SELECT * FROM answers EXCEPT WHERE question_id='$data[i]'") or die(mysql_error());
            return ($result2);
            }
    }else{
        return false;}
}

跟随位于index.php的代码,我试图从DB_Functions.php接收结果

if($tag == 'getQuestions'){
                $username = $_POST['username'];
                    $getAllQuestions = $db->getQuestions($username);
            $data = array();
            while($row = mysql_fetch_assoc($getAllQuestions)) { //I'm getting ERROR on this line
            $data[] = array(
            $response["getAllQuestions"]["id"] = $row["id"],
            $response["getAllQuestions"]["username"] = $row["username"],
            $response["getAllQuestions"]["question_id"] = $row["question_id"],
            $response["getAllQuestions"]["question"] = $row["question"],
            $response["getAllQuestions"]["tag1"] = $row["tag1"],
            $response["getAllQuestions"]["tag2"] = $row["tag2"],
            $response["getAllQuestions"]["tag3"] = $row["tag3"],
            $response["getAllQuestions"]["question_time"] = $row["question_time"]);}
            echo json_encode($data);
                    }

以下是logcat消息:

06-26 21:08:13.920: D/JSON(478): <b>Warning</b>:  mysql_fetch_assoc() expects parameter 1 to be resource, null given in <b>C:\xampp\htdocs\android_php_1\index.php</b> on line <b>178</b><br />

由于

1 个答案:

答案 0 :(得分:2)

MySQL不支持EXCEPT关键字,因此查询会将null返回到$result2,因为没有形成结果集,这就是您收到该错误的原因。相反,您实际上可以将这两个查询合并为一个:

SELECT
    a.*
FROM
    answers a
LEFT JOIN
    (
        SELECT DISTINCT question_id
        FROM answered
        WHERE ? IN (asked_by, answered_by)
    ) b ON a.question_id = b.question_id
WHERE 
    b.question_id IS NULL 

getQuestions()功能中,您可以用以下内容替换整个内容:

public function getQuestions($username) {
    $filtered_username = mysql_real_escape_string($username);
    $sql = "
        SELECT a.*
        FROM answers a
        LEFT JOIN
        (
            SELECT DISTINCT question_id
            FROM answered
            WHERE '$filtered_username' IN (asked_by, answered_by)
        ) b ON a.question_id = b.question_id
        WHERE b.question_id IS NULL";

    return mysql_query($sql) ?: false;
}

另请注意,您以前的代码容易受到SQL注入攻击。在我的解决方案中,我首先通过mysql_real_escape_string()传递了用户名变量以防止这种情况(不如准备好的语句,但仍然比没有好)。 从不 将用户输入直接传递给查询。

相关问题