2012-06-26 50 views
1

我试图得到特定用户回答或要求的问题的id,而不是尝试使用这些id的问题,并得到问题,其中id与从中检索到的id不同第一个查询。当试图实现这个我得到一个mysql_fetch_assoc()相关的错误/警告,结果我的程序崩溃。mysql_query里面for循环给出mysql_fetch_assoc相关的错误/警告

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

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 /> 

感谢

+0

可能的重复[Warning:mysql_fetch_ *期望参数1是资源,布尔给定错误](http://stackoverflow.com/questions/11674312/warning-mysql-fetch-expects-parameter-1-tobe -resource布尔给出的误差) – j0k

回答

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()传递了用户名变量,以防止这种情况发生(不如准备好的语句,但仍比没有好)。 绝不会将用户输入直接传递到查询中。