所以我有一个表单看起来是这样的。
<form action="thanks.php" method="post" class="niceform" name="myform">
<table>
<tr>
<td><label for="company_name">Company Name</label></td>
<td><input type="text" name="company" value="" size="38" /></td>
</tr>
// and so on我有javascript的验证。但问题是,当我直接从localhost/mysite/form/timks.php转到thanks.php时,当我查看phpmyadmin时,会插入一个空行。Thanks.php看起来是这样的。
<?php
// open the connection
$conn = mysql_connect("localhost", "root", "password");
// pick the database to use
mysql_select_db("company_register",$conn);
$sql = "INSERT INTO `tblsignups` VALUES ('NULL', '$_POST[company]', '$_POST[email]', '$_POST[phone]', '$_POST[address]', '$_POST[comments]', '$_POST[contact_person]')";
$result = mysql_query($sql, $conn) or die(mysql_error());
mysql_close($conn);
?>
// And I have a thank you msg I display如果有人应该直接访问thanks.php,我告诉他们先填写表单,不要在数据库中放入任何内容,我该如何检查
发布于 2011-09-20 17:11:02
下面是一个草图示例
收到POST数据后,必须对其进行检查并发出错误标志
如果出现某些错误,请重新显示表单而不是保存表单
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?> 并修改您的表单以使其能够显示错误
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>发布于 2011-09-20 17:02:33
您需要检查表单是否已提交。你可能想要这样的东西:
<?php
if ($_POST)
{
// open the connection
$conn = mysql_connect("localhost", "root", "password");
// pick the database to use
mysql_select_db("company_register",$conn);
$sql = "INSERT INTO `tblsignups` VALUES ('NULL', '$_POST[company]', '$_POST[email]', '$_POST[phone]', '$_POST[address]', '$_POST[comments]', '$_POST[contact_person]')";
$result = mysql_query($sql, $conn) or die(mysql_error());
mysql_close($conn);
}
?>发布于 2011-09-20 17:02:56
您可以将所有内容检查为
if(empty($_POST['company']))
{
//redirect or show error msg that its required
}
else
{
//do what you want
}所有人都是如此。
如果你已经发布了表单,$_POST将始终为真,所以当你必须检查空值时,你必须像这样检查所有的值。
if(empty($_POST['company']) || empty($_POST['email']) || empty($_POST['user']))诸若此类。
https://stackoverflow.com/questions/7482566
复制相似问题