Php 验证要发送到数据库的表单字段

Php 验证要发送到数据库的表单字段,php,Php,我目前正在通过我创建的表单使用数据库中的信息: <form method="post" action="send.php"> <input type="text" name="firstname" id="firstname" class="yourinfo" ><br/> <input type="text" name="lastname" id="lastname" value="Last Name" onFocus=this.val

我目前正在通过我创建的表单使用数据库中的信息:

<form method="post" action="send.php">
    <input type="text" name="firstname" id="firstname" class="yourinfo" ><br/>
    <input type="text" name="lastname" id="lastname" value="Last Name" onFocus=this.value='' class="yourinfo"><br/>
    <input type="text" name="email" id="email" value="Email Address" onFocus=this.value='' class="yourinfo"><br/>
    <input type="text" name ="date" id="datepicker" value="Enter Your Prediction" onFocus=this.value='' class="yourinfo"><br/>
    <input type="submit" value="submit" >
    </form>

您至少可以检查它们是否为空,并使用正则表达式验证电子邮件。 还可以对数据库使用PDO,它可以保护您免受各种形式的SQL注入


互联网上有很多关于PDO的教程。

调用
mysql\u real\u escape\u string()
了解SQL语句中要使用的所有变量

$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$datepicker = mysql_real_escape_string($_POST['date']);
具有讽刺意味的是,你不需要逃避的一件事是
$new\u date
,因为你已经可以确定它是有效且安全的
Y-m-d
(或者如果日期不正确,它是
FALSE
)。但是不痛

$query="INSERT INTO table (id, firstname, lastname, email, date) 
  VALUES (NULL, '".$firstname."', '".$lastname."', '".$email."',   '".mysql_real_escape_string($new_date)."')";
所有的引用和连接都有点混乱。在PHP中,可以使用如下字符串插值:

$query="INSERT INTO table (id, firstname, lastname, email, date) 
  VALUES (NULL, '$firstname', '$lastname', '$email', '".mysql_real_escape_string($new_date)."')";

我告诉你:)你甚至还保留了我的大写字母“必须”作为强调!您是否在连接线之前使用mysql\u real\u escape\u字符串?您应该将每个mysql_real_escape_字符串行($firstname=mysql_real_escape_string($\u POST['firstname']);等等)移动到连接到数据库的行之后。它需要连接到数据库以确定要转义的字符。啊。。。。这似乎已经解决了它。很抱歉,听起来很愚蠢,但是这样做是否可以保护我免受人们从表单侵入数据库的攻击?当你提交表单时,使用它只是返回了一堆错误form@Gezzamondo错误是什么?如果我们知道它们是什么,我们就能修复它们。另外,去掉
'NULL'
的引号。我这里没有足够的字符来发布错误,你的电子邮件地址和我的电子邮件you@Gezzamondo不,不,不要在评论或电子邮件中发布它们。将其发布为对上述原始问题的编辑。
$query="INSERT INTO table (id, firstname, lastname, email, date) 
  VALUES (NULL, '".$firstname."', '".$lastname."', '".$email."',   '".mysql_real_escape_string($new_date)."')";
$query="INSERT INTO table (id, firstname, lastname, email, date) 
  VALUES (NULL, '$firstname', '$lastname', '$email', '".mysql_real_escape_string($new_date)."')";