mysql_query()的问题;说预期的资源

joh*_*een 1 php mysql

我有这个php文件.标记为粗体的行显示错误:"mysql_query()将参数2作为资源使用.嗯,在我评论过的行上的类似语法'没有错误??' 工作得很好.

 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;
?>
Run Code Online (Sandbox Code Playgroud)

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

<?php
 $conn= mysql_connect("localhost","root","password");
 mysql_select_db("quiz",$conn);
?>
Run Code Online (Sandbox Code Playgroud)

Sev*_*Sev 5

$result2=mysql_query($sql2,$conn);
Run Code Online (Sandbox Code Playgroud)

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

虽然你可以使用这个建议来使$ conn 全局化,但通常更好的做法是不要为了全球化而使全局化.

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