我在php和mysql中进行测验。现在我从数据库中提取问题,假设我不知道数据库中没有问题。我希望我的代码能够获取数据,直到问题没有结束,但我不知道那些问题。那么哪种条件适用。获取数据的代码。
<?php
function ravi($qid=NULL)
{
$con = mysql_connect('localhost', 'root', '') or die(mysql_error());
$db = mysql_select_db('quiz', $con) or die(mysql_error());
$q="select * from question where qno=$qid";
$rq=mysql_query($q,$con);
if(!$rq)
{
echo " the sql query faiiled to work ";
}
else
{
while ($sub_row=mysql_fetch_array($rq))
{
$id=$sub_row["qno"];
$question=$sub_row["question"];
$option1=$sub_row["option1"];
$option2=$sub_row["option2"];
$option3=$sub_row["option3"];
$option4=$sub_row["option4"];
echo "<h5>Q".$id." : ".$question."</br></h5>";
echo"</br>
<br>
<h4><input type= radio id='1' name=\"{$id}\" value=\"{$option1}\">$option1</h4>
</br>
<h4><input type= radio id='2' name=\"{$id}\" value=\"{$option2}\">$option2</h4>
</br>
<h4><input type= radio id='3' name=\"{$id}\" value=\"{$option3}\">$option3</h4>
</br>
<h4><input type= radio id='4' name=\"{$id}\" value=\"{$option4}\">$option4</h4>
</br></br>";
}
}}
?>
答案 0 :(得分:2)
if (mysql_num_rows($rq) == 0) {
echo "database is empty.";
}
但你应该停止使用mysql_*
,正如评论中所说的那样。
答案 1 :(得分:0)
为了大大增强安全性,您应该使用mysqli
使用预准备语句(自动转义的类型转换变量),PHP webpage。
这样的事情:
# Database credentials
$mysqlsrv = "localhost";
$mysqlusr = "myusr";
$mysqlpsw = "mypsw";
$mysqldb = "mydb";
# Connect to database in the secure "prepared statement" way
$mysqli = new mysqli($mysqlsrv,$mysqlusr,$mysqlpsw,$mysqldb);
# Check for database connection errors
if(mysqli_connect_errno()) {
echo "Cannot connect to database";
exit();
}
$searchNum = 1;
$searchStr = "Text";
$query = "SELECT question FROM mytable WHERE num=? OR str=?";
if($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("is",$searchNum,$searchStr);
$stmt->execute();
$stmt->bind_result($question);
if($stmt->fetch()) {
while($stmt->fetch()) {
echo "$question<br />";
}
} else {
echo "Could not find any post in table";
} // if($stmt->fetch())
$stmt->close();
} // if($stmt = $mysqli->prepare($query))