1

我试图获取特定用户回答或询问的问题的 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 />

谢谢

4

1 回答 1

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 注入的影响。在我的解决方案中,我首先通过 username 变量mysql_real_escape_string()来防止这种情况(不如准备好的语句,但总比没有好)。切勿将用户输入直接传递到查询中。

于 2012-06-26T18:31:38.683 回答