[英]Problem with mysql_query() ;Says resource expected
我有這個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;
?>
這是文件connect.php。 對於其他PHP文檔來說,它工作得很好。
<?php
$conn= mysql_connect("localhost","root","password");
mysql_select_db("quiz",$conn);
?>
$result2=mysql_query($sql2,$conn);
$ conn不在函數范圍內定義(即使您之前包含了connect.php文件也是如此)。
盡管您可以使用該建議使$ conn 全局化 ,但通常最好的做法是不只是為了全球化而使全局化。
我寧可將$ conn作為參數傳遞給函數。 這樣,您可以重復使用通過不同連接編寫的相同函數。
沒有將$ conn聲明為全局變量,因此該函數無法訪問它,因為它未在其中定義。
只需添加
global $conn;
在該函數的頂部,以允許它訪問$ conn。
或者,您可以從mysql_query()語句中刪除$ conn。 默認情況下,它將使用當前連接(如下注釋中所述)。
您在哪里設置$ conn? 您似乎未在該函數中設置連接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.