php - mysql_query() 的问题;表示需要资源

标签 php mysql

我有这个 php 文件。标记为粗体的行显示错误:“mysql_query() expecets parameter 2 to be a resources”工作正常。

 function checkAnswer($answerEntered,$quesId)
 {
  //This functions checks whether answer to question having ques_id = $quesId is satisfied by $answerEntered or not

  $sql2="SELECT keywords FROM quiz1 WHERE ques_id=$quesId";
  **$result2=mysql_query($sql2,$conn);**
  $keywords=explode(mysql_result($result2,0));

  $matches=false;
  foreach($keywords as $currentKeyword)
  {
   if(strcasecmp($currentKeyword,$answerEntered)==0)
   {
    $matches=true;
   }
  }

  return $matches;

 }

 $sql="SELECT answers FROM user_info WHERE user_id = $_SESSION[user_id]";
 $result=mysql_query($sql,$conn);         // No error??
 $answerText=mysql_result($result,0);

 //Retrieve answers entered by the user
 $answerText=str_replace('<','',$answerText);
 $answerText=str_replace('>',',',$answerText);
 $answerText=substr($answerText,0,(strlen($answerText)-1));
 $answers=explode(",",$answerText);

 //Get the questions that have been assigned to the user.
 $sql1="SELECT questions FROM user_info WHERE user_id = $_SESSION[user_id]";
 **$result1=mysql_query($sql1,$conn);**
 $quesIdList=mysql_result($result1,0);
 $quesIdList=substr($quesIdList,0,(strlen($quesIdList)-1));
 $quesIdArray=explode(",",$quesIdList);



 $reportCard="";
 $i=0;
 foreach($quesIdArray as $currentQuesId)
 {
  $answerEnteredByUser=$answers[$i];

  if(checkAnswer($answerEnteredByUser,$currentQuesId))
  {
   $reportCard=$reportCard+"1";
  }
  else
  {
   $reportCard=$reportCard+"0";
  }
  $i++;
 }

 echo $reportCard;
?>

这是文件 connect.php。它适用于其他 PHP 文档。

<?php
 $conn= mysql_connect("localhost","root","password");
 mysql_select_db("quiz",$conn);
?>

最佳答案

$result2=mysql_query($sql2,$conn);

$conn 未在您的函数范围内定义(即使您在此之前包含 connect.php 文件。

虽然您可以使用建议使 $conn global,但通常更好的做法是不要仅仅为了全局化而将某些东西设为全局。

我会改为将 $conn 作为参数传递给函数。这样,您就可以重用使用不同连接编写的相同函数。

关于php - mysql_query() 的问题;表示需要资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3023915/

相关文章:

php - 如何列出最受关注的人帐户以及其他帐户

mysql - 由于选择查询而锁定表?

java - 在 vaadin 的网格中显示 JSON 数据

mysql - 每个用户最多显示3笔交易

php - 从当前 url 获取 slug

php - 图像在 FB.ui 中不起作用

java - 在 Spring 中将正则表达式查询与 hibernate 一起使用

mysql - MySQL 中的时间旅行 View

php - MYSQL - 使用 CRYPT 进行散列时出现特殊字符问题

php - 在数组中寻找字符串