将表单数据写入SQL数据库

时间:2017-02-21 23:18:38

标签: php sql

我不断出现意外情况&#34 ;;"。我无法弄清楚问题是什么。如果有人有任何建议我会非常感激。

send_post.php

<?php
//Create connect
$connect = mysqli_connect("localhost","tasks","tasks15!","tasks");
//Sending form data to sql db.
mysqli_query ($connect,"INSERT INTO tasks (CompanyName, ContactName,  Address1, Address2, City, State, Zip, Phone1, Phone2, Fax1)
VALUES ('$_POST[tasks_CompanyName]', '$_POST[tasks_ContactName]',     '$_POST[tasks_Address1]', '$_POST[tasks_Address2]' ,'$_POST[tasks_City]','$_POST[tasks_State],'$_POST[tasks_Zip]', '$_POST[tasks_Phone1]','$_POST[tasks_Phone2]','$_POST[tasks_Fax1]');"

?>

的index.html

<form action="send_post.php" method="post">
<h1>Customer Information</h1>

<h3>Company Name</h3> <input type="text" name="tasks_CompanyName"> <br>
<h2>Customer Name</h2><h3>First Name</h3> <input type="text" name="tasks_fname"><br>
<h3> Last Name</h3><input type="text" name="tasks_lname"><br>
<h3> Address 1 </h3>  <input type="text" name="tasks_Address1"><br>

<h3> Address 2</h3>   <input type="text" name="tasks_Address2"><br>

<h3>City</h3><input type="text" name="tasks_City"><br>

<h3>State</h3> <input type="text" name="tasks_State"><br>

<h3>Zip</h3>    <input type="text" name="tasks_Zip"><br>

<h3>Phone 1</h3><input type="text" name="tasks_Phone1"><br>

<h3>Phone 2</h3> <input type="text" name="tasks_Phone2"><br>

<h3>Fax 1</h3>     <input type="text" name="tasks_Fax1"><br>


<input type="submit">
</form>

2 个答案:

答案 0 :(得分:1)

mysqli_query ($connect,"INSERT INTO tasks (CompanyName, ContactName,  Address1, Address2, City, State, Zip, Phone1, Phone2, Fax1)
VALUES ('$_POST[tasks_CompanyName]', '$_POST[tasks_ContactName]',     '$_POST[tasks_Address1]', '$_POST[tasks_Address2]' ,'$_POST[tasks_City]','$_POST[tasks_State],'$_POST[tasks_Zip]', '$_POST[tasks_Phone1]','$_POST[tasks_Phone2]','$_POST[tasks_Fax1]');"

这一行有一些错误。 $_POST是一个数组,因此您必须使用密钥的名称访问该值 - 例如$_POST["tasks_Address1"]而不是$_POST[tasks_Address1]

你还在行尾的引号内部得到了分号:'$_POST[tasks_Fax1]');"。你想把这个分号放在外面:'$_POST[tasks_Fax1]')";

您的SQL也可能受SQL注入的影响。阅读一些资源,例如How can I prevent SQL injection in PHP,了解如何使代码免受恶意输入的影响。

答案 1 :(得分:0)

您可以尝试添加&#34;);&#34;在mysqli_query行的末尾丢失。

send_post.php:5

<?php
mysqli_query ($connect,"INSERT INTO tasks
  (CompanyName, ContactName, Address1, 
   Address2, City, State, Zip, Phone1,
   Phone2, Fax1)
VALUES
  ('$_POST[tasks_CompanyName]', '$_POST[tasks_ContactName]',
   '$_POST[tasks_Address1]',    '$_POST[tasks_Address2]',
   '$_POST[tasks_City]',        '$_POST[tasks_State],
   '$_POST[tasks_Zip]',     '$_POST[tasks_Phone1]',   
   '$_POST[tasks_Phone2]',  '$_POST[tasks_Fax1]'
  );");
?>

请注意,记录没有验证的POST数据会很危险,因为它可能导致XSS和SQL注入攻击。