php验证代码格式

时间:2013-11-09 01:08:18

标签: php html

好的,我有这个MySQL数据库表单,我正在尝试添加验证。经过2天的战斗,我想我会得到一些建议。希望从下拉列表和名字,电话,电子邮件中选择的项目都是必需的。然后我想验证在放入数据库之前,名字,姓氏,电话(不必是任何特殊格式),电子邮件和评论中的数据都是可接受的格式。以下是我到目前为止的情况:

 <?php 
include('inc_header.php');
if(isset($_POST['add']))
 {
 require('dbcon.php');
 if(! get_magic_quotes_gpc() )
{
$Id = addslashes ($_POST['Id']);
$List = addslashes ($_POST['List']);
$Firstname = addslashes ($_POST['Firstname']);
$Lastname = addslashes ($_POST['Lastname']);
$Phone = addslashes ($_POST['Phone']);
$Email= addslashes ($_POST['Email']);
$Calltime = addslashes ($_POST['Calltime']);
$Comment = addslashes ($_POST['Comment']);

}
else
{
$Id = $_POST['Id'];
$Date = $_POST['Date'];
$List = $_POST['List'];
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Calltime = $_POST['Calltime'];
$Comment = $_POST['Comment'];
 }

 $error = '';

 //put chosen function here
  function validate_Firstname($input, $pattern = "/([A-Za-z0-9])")
 {
    return !preg_match($pattern, $input);
   }

  function validate_Phone($input, $pattern = "/([A-Za-z0-9])")
 {
    return !preg_match($pattern, $input);
  }
 function isValidEmail( $Email ){
    return filter_var( $Email, FILTER_VALIDATE_EMAIL );
 }

  //get values and validate each one as required
  $List = mysql_real_escape_string($_POST['List']);
     if(!$List){ $error .= "Please choose one<br />"; }

  $Firstname = mysql_real_escape_string($_POST['Firstname']);
    if(!$Firstname){ $error .= "First name is required<br />"; }

//get values and validate each one as required
  $Lastname = mysql_real_escape_string($_POST['Lastname']);
    if(!$Lastname){ $error .= "Last name is required<br />"; }

  //repeat for each field
  $Email = mysql_real_escape_string($_POST['Email']);
    if(!isValidEmail($Email)){ $error .= "The email entered is invalid<br />"; }

  //and so on...

  if(!$error){
     //add insert into database code here

 $sql = "INSERT INTO contacts ".
   "(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
 "VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment')     ";
 mysql_select_db('hmintcwa_contacts');
 $retval = mysql_query( $sql, $conn );
 if(! $retval )
 {
  die('Could not enter data: ' . mysql_error());
 }
 echo "Entered data successfully<br /><br /><a href=contactsadd.php><font       color=#000000>Back</font></a>\n";
 mysql_close($conn);
}
else
 {

 ?>

 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
 <table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
 <input type="hidden" name="Id" id="Id">
 <tr>
 <td bgcolor="#e9e9e9" align="right">Requested Info</td>
 <td bgcolor="#ffffff" align="left"><select name="List">
 <option value="0" > Please Choose One </option>
 <option value="Market Analysis" > Market Analysis </option>
 <option value="Consultation" > Consultation </option></select></td></tr>
  <tr>
 <td bgcolor="#e9e9e9" align="right">Date</td>
 <input name="Date" type="hidden" id="Date" value="<? print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><? print(Date("l F d, Y")); ?></td>
</tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Firstname</td>
 <td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Lastname</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Lastname"  size="20" id="Lastname"></td>
 </tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Phone</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
 <tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Email"  size="20" id="Email"></td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Calltime"  size="20" id="Calltime">  &nbsp;&nbsp; If none put N/A</td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Comment</td>
 <td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">&nbsp;</td>
 <td bgcolor="#ffffff" align="center"><br>
 <input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>&nbsp;
 </td>
 </tr>
 </table>
 </form>
 <br>&nbsp;</center>
 <?php
 }
  ?>
   </body>
       </html>

到目前为止,我一直在追逐错误消息。请原谅格式我试图学会温柔。

2 个答案:

答案 0 :(得分:2)

您的查询参数是向后的,您应该使用mysqli_。这是正确的顺序。

$retval = mysqli_query($conn, $sql);

mysqli_query documentation

答案 1 :(得分:0)

您需要此声明的结束括号:(if(!$error){

修改:您遗失的}实际上是if(isset($_POST['add']))的结束括号,而不是魔术引号。遗憾!

     //and so on...

    if(!$error)
    {
      //add insert into database code here

       // this probably won't run right... 
       // you're missing a ( after the word values...
       // insert into tablename (id, name, stuff) values (1,'gloomy','stuff); 

       // this part of your statement is not correct:  "VALUES'$Id,','$Date',
       // and the commas are off, too.

       $sql = "INSERT INTO contacts ".
               "(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
               "VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment')     ";

       // print your SQL here to make sure it is correct.  
       // copy and paste it to run it directly in the DB. if it won't run there
       // it won't run here
       print $sql."<br/>"; 

       mysql_select_db('hmintcwa_contacts');
       $retval = mysql_query( $sql, $conn );

       if(! $retval )  {
          die('Could not enter data: ' . mysql_error());
       }

       echo "Entered data successfully<br /><br /><a href=contactsadd.php><font       color=#000000>Back</font></a>\n";
       mysql_close($conn);

    } // <-------- you're missing this closing bracket

} // this ends the statement for  if(isset($_POST['add']))  { .... 
else
{
    // REMOVE this... or else it will print the world else somewhere
    // i put this here to debug...
    print "else<br/>";

?>

格式化代码有很多帮助

编辑:查看代码,到处都有很多小问题。我不是故意的。我只是说...为什么不尝试将代码分解成更小的部分并确保所有部分在将它们放在一起之前自行编译和正常工作?这是一次解决所有问题。只需在需要时尝试转储变量(特别是数组),每次编写新块时,确保它正常工作并确保其他所有内容仍能正常工作。然后,继续前进......以这种方式隔离问题更容易。


这对我有用。它使用了pdo。哦,现在你不需要担心sql注入了。这几乎完全照顾它。像所有事情一样,总是有各种各样的方法,但你不需要检查魔术引号,你不需要逃避任何事情。进行参数化处理所有这些。

编辑:所以...当你编写代码时......不要写一大堆东西而然后看看它是否全部有效。写几行。测试。写些更多。测试。确保新的东西有效。确保旧的东西仍然有效。写一点。我完全不知道你是如何在这么多小问题上取得这么多的。我不是故意的。但是,在lil块中编写代码。甚至逻辑。总是再测试一切,然后继续前进。

我将调试语句留在那里...... print_r($array)var_dump(variable),以便您可以看到这些内容是如何设置的,您的值在哪里来自,什么一切都在什么地方,如何使用它们,在哪里放置它们。它会打印出奇怪的东西。将其注释掉或删除它们。

我知道有更多mysql_功能的教程,但它们已经陈旧,根本不安全。如果您在使用PDO时遇到问题,只需使用您的错误,问题和代码回到StackOverflow,然后写一个免责声明“您知道mysql_功能不好但是pdo更难学”,人们将会很乐意提供帮助,因为它好多了。

这些是重要的PDO页面:

和代码......

<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

// include('inc_header.php');


function validate_Firstname($input, $pattern = "/([A-Za-z0-9])") {
   return !preg_match($pattern, $input);
}

function validate_Phone($input, $pattern = "/([A-Za-z0-9])") {
   return !preg_match($pattern, $input);
}

function isValidEmail($Email) {
   return filter_var($Email, FILTER_VALIDATE_EMAIL);
}

// ====================================================================================
// ====================================================================================

if (!empty($_POST)) {
   print "<pre>This is your \$_POST array \n\n".print_r($_POST,true)."</pre>"; 
}

$error = '';

if (isset($_POST['add'])) 
{
   // require('dbcon.php');
   $conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');

   // what if the array index ['whatever'] doesn't exist?  errors.  
   // so we need to check and make sure it is set... then assign.  
   // this also gives us a blank default value, which is nice.... 
   $id        = isset($_POST['Id'])        ? $_POST['Id']        : 'NULL'; 
   $date      = isset($_POST['Date'])      ? $_POST['Date']      : '';  
   $list      = isset($_POST['List'])      ? $_POST['List']      : '';  
   $firstname = isset($_POST['Firstname']) ? $_POST['Firstname'] : ''; 
   $lastname  = isset($_POST['Lastname'])  ? $_POST['Lastname']  : ''; 
   $phone     = isset($_POST['Phone'])     ? $_POST['Phone']     : ''; 
   $email     = isset($_POST['Email'])     ? $_POST['Email']     : '';  
   $calltime  = isset($_POST['Calltime'])  ? $_POST['Calltime']  : '';  
   $comment   = isset($_POST['Comment'])   ? $_POST['Comment']   : '';   

   if (!$list) {
      $error .= "Please choose one<br />";
   } 
   if (!$firstname) {
      $error .= "First name is required<br />";
   } 
   if (!$lastname) {
      $error .= "Last name is required<br />";
   } 
   if (!isValidEmail($email)) {
      $error .= "The email entered is invalid<br />";
   }

   var_dump($error); 

   if (!$error) 
   {     
      $stmt = $conn->prepare("INSERT INTO contacts (id, date, list, firstname, lastname, phone, email, calltime, comment) \n". 
                              " VALUES (:id, :date, :list, :firstname, :lastname, :phone, :email, :calltime, :comment) "); 

      $success = $stmt->execute(array(':id'=>$id, ':date'=>$date, ':list'=>$list, ':firstname'=>$firstname, 'lastname'=>$lastname,  
                                      ':phone'=>$phone, ':email'=>$email, ':calltime'=>$calltime, ':comment'=>$comment)); 

      if (!$success) 
      { 
          echo "\nPDO::errorInfo():\n"; 
          print "<pre>".print_r($dbh->errorInfo(),true)."/<pre>"; 
      }  
      else 
      {
         print "it worked!  the new row's ID is ".$conn->lastInsertId()."...!!!<br/>";
      }

      echo "Entered data successfully<br/><br/>";


   } // end of  if (!$error) { ... }  
   else 
   {  
      print "$error<br/>";
   }

   echo "<a href='contactsadd.php' style='font-color=#000000'>Back</a>\n";

} // end of if(isset($_POST['add']))  { ... }
else
{ 

// ====================================================================================
// ====================================================================================
?>
 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
 <table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
 <input type="hidden" name="Id" id="Id">
 <tr>
 <td bgcolor="#e9e9e9" align="right">Requested Info</td>
 <td bgcolor="#ffffff" align="left"><select name="List">
 <option value="0" > Please Choose One </option>
 <option value="Market Analysis" > Market Analysis </option>
 <option value="Consultation" > Consultation </option></select></td></tr>
  <tr>
 <td bgcolor="#e9e9e9" align="right">Date</td>
 <input name="Date" type="hidden" id="Date" value="<?php print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><?phpprint(Date("l F d, Y")); ?></td>
</tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Firstname</td>
 <td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Lastname</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Lastname"  size="20" id="Lastname"></td>
 </tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Phone</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
 <tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Email"  size="20" id="Email"></td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
 <td bgcolor="#ffffff" align="left"><input type="text" name="Calltime"  size="20" id="Calltime">  &nbsp;&nbsp; If none put N/A</td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">Comment</td>
 <td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
 <tr>
 <td bgcolor="#e9e9e9" align="right">&nbsp;</td>
 <td bgcolor="#ffffff" align="center"><br>
 <input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>&nbsp;
 </td>
 </tr>
 </table>
 </form>
 <br>&nbsp;</center>
 <?php
 }
 ?>