如何在PHP中验证表单?

时间:2013-05-16 14:50:48

标签: php forms post submit

如何验证此表单。当用户提交而不选择选项时,他必须收到提醒。

我的代码:

echo "<form method='post' id='submit' action='checkresult.php'>";
$sql="SELECT * FROM cquestions where showdate='$today' limit 2";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<p>" . $row['cqtext'] . "</p>";
$sql2="SELECT * FROM canswers where cqid=".$row['cqid'];
$result2=mysql_query($sql2);
while($row2=mysql_fetch_assoc($result2))
{
echo "<input type='radio' name='".$row['cqid']."' value='".$row2['cqans']."' />".$row2['aatext']; }
}

2 个答案:

答案 0 :(得分:1)

你要找的是$ _POST变量。当您提交使用action ='checkresult.php'的表单时,然后在checkresult.php上,您将能够使用$ _POST命令来检索变量值。

test.php页面(使用表单输出)

<form method='post' id='submit' action='checkresult.php'>
<input type='radio' name='the_name' value='the_value' />
<input type="submit">
</form>

<强> checkresult.php:

echo $_POST["the_name"];
// Output = the_value

答案 1 :(得分:0)

您使用的方法是正确的,但语法错误:

<?php
$marks+=$_POST['$cqid']; //Not Correct!
//1st You haven't defined $cqid. Its $qid.
//2nd You can't use a variable inside single quotes.
//PHP will consider it as normal String. But you can use it inside double quotes.
//But remember you can't use array ($row['cqid']) inside double quotes.
?>

<小时/> 这是正确的方法:

<?php
while ($row = mysql_fetch_array($result)) {
    //$qid=$row['cqid'];
    //$marks+=$_POST[$qid]; //Correct!
    //But, Not needed You can directly use $row['cqid'] as an index.
    $marks+=$_POST[$row['cqid']];
}
?>

<小时/> 更新:[用于调试]

while ($row = mysql_fetch_array($result)) {
    $marks+=$_POST[$row['cqid']];
    echo $marks.'<br/>';
}
$insert="insert into result(email,marks)values('$email',$marks)";
$insert = mysql_query($insert);
if(!$result) {
    die('Unable to perform insert action. The following error occured: '.  mysql_error());
} else {
   echo 'The following Query: <b>'.$insert.'</b> executed successfully!';
}

同时检查$email的值,我无法从中获取该值。

并且$login_session = $_POST['email'];此行重复两次,但我确定此值始终为空,因为在 test.php 中您评论了以下行:

echo "<input type='hidden' name='email' value='email' />";

值属性:value='email'显然似乎错了!

检查所有这些东西,我想你现在可以随身携带...... :)如果没有,我仍然很乐意帮助你......

更新:[用于设置查询限制]

SELECT * FROM `cquestions` LIMIT 0,3;
//Will fetch first three records from cquestions.
SELECT * FROM `cquestions` LIMIT 2,3;
//Will fetch 3rd, 4th and 5th records from cquestions.