确定MySQL数据库中是否存在行

时间:2011-10-17 05:36:27

标签: php mysql sql

我收到的错误消息为:Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in ... on line 45

源自代码的这一部分:

//Only allow the input of empty responses once
foreach ($questionIDs as $questionID) {
    $query = "SELECT response_id FROM quiz_response " .
    "WHERE question_id = '".$questionID."' AND user_id = '".$_SESSION['user_id']."'"; 
    $result = mysqli_query($dbc, $query);
}
if (($row = mysqli_fetch_array($result)) == false) {
    // Create empty responses in 'quiz_response' table if none exist already
    foreach ($questionIDs as $questionID) {
        $query2 = "INSERT INTO quiz_response (user_id, question_id) VALUES ('" . $_SESSION['user_id'] . "', '" . $questionID . "')";
        mysqli_query($dbc, $query2);
    } 
}

第45行是if (($row = mysqli_fetch_array($result)) == false) {

脚本仍然可以正常工作,但是,它也会在页面上生成错误消息(上面)。基本上,我正在尝试确保在为此用户创建行之前,还没有与此特定用户和question_id关联的列。为此,我对表进行查询,如果没有符合条件的行,则创建它们。

我在如何解决问题上画了一个空白。我尝试了很多不同的方法,并没有取得任何成功。需要一个外部视角......我感谢任何帮助或输入。谢谢!

3 个答案:

答案 0 :(得分:1)

首先确保您使用以下数据connected进入数据库:

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

然后你像这样尝试它,正如在问题的评论中指出你的循环结构只为最后$questionID插入新记录,如果它不存在,因为插入逻辑在你检查是否存在的循环之外记录:

//Only allow the input of empty responses once
foreach ($questionIDs as $questionID) {
    $query = "SELECT response_id FROM quiz_response " .
    "WHERE question_id = '".$questionID."' AND user_id = '".$_SESSION['user_id']."'"; 
    $result = mysqli_query($dbc, $query);

    if (($row = mysqli_fetch_array($result)) == false) {
        // Create empty responses in 'quiz_response' table if none exist already
        foreach ($questionIDs as $questionID) {
            $query2 = "INSERT INTO quiz_response (user_id, question_id) 
            VALUES ('" . $_SESSION['user_id'] . "', '" . $questionID . "')";
            mysqli_query($dbc, $query2);
        } 
    }
}

答案 1 :(得分:1)

你可以这样做:

foreach ($questionIDs as $questionID) {
  $query = "SELECT response_id FROM quiz_response " .
    "WHERE question_id = '".$questionID . 
    "' AND user_id = '".$_SESSION['user_id']."'"; 
  $result = mysqli_query($dbc, $query);

  //using count to make sure that there are no existing records:
  $count = count($result);
  if ($count == 0) {
    // Create empty responses in 'quiz_response' table if none exist already
    foreach ($questionIDs as $questionID) {
      $query2 = "INSERT INTO quiz_response (user_id, question_id) 
        VALUES ('" . $_SESSION['user_id'] . "', '" . $questionID . "')";
        mysqli_query($dbc, $query2);
    } 
  }
}

答案 2 :(得分:-3)

该错误是因为您的查询返回null并且无法从空查询中获取数组。

你这里也有一个错字:

$result = mysqli_query($dbc, $query); 

应该是:

$result = mysql_query($dbc, $query); 
你有额外的我。这似乎是导致问题的原因。

另外,你必须做$ result = mysql_query($ query,$ dbc);而不是相反。