如何阻止PHP向MYSQL数据库添加空白行/字段 [英] How to stop PHP from adding blank row/fields to the MYSQL database

查看:280
本文介绍了如何阻止PHP向MYSQL数据库添加空白行/字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个看起来像这样的表格.

So I have a form that looks so.

<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进行了验证.但是问题是,当我直接从本地主机/mysite/form/thanks.php访问thank.php时,当我查看phpmyadmin时会插入一个空行. Thanks.php看起来像这样.

I have the validation by javascript. But the problem is that when I go directly to thanks.php from localhost/mysite/form/thanks.php I have an empty row that is inserted when I look at phpmyadmin. Thanks.php looks like so.

<?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

我如何检查是否有人应该直接转到thank.php,我告诉他们首先填写表格,并且不要在数据库中放置任何内容

How do I check that if some one should directly go to thanks.php I tell them to go fill the form first and do not put anything on the database

推荐答案

这是草图示例

收到POST数据后,您必须检查它并提出错误标志
如果出现某些错误,请显示表格而不是保存表格

after receiving POST data you have to check it and raise error flag
in case of some errors show the form back instead of saving it

<?  
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';
?>  

并修改表格以使其显示错误

and modify your form to make it possible to show errors

<? 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>

这篇关于如何阻止PHP向MYSQL数据库添加空白行/字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆