使用PHP将表单数据添加到数据库

时间:2013-12-27 11:48:04

标签: php html forms mysqli

您好,我正在努力让我的表单将其数据发布到MySQL数据库。

我的配置文件设置如下:

 // server info
 $server = 'localhost';
 $user = 'root';
 $pass = '';
 $db = 'cms';

 // connect to the database
 $mysqli = new mysqli($server, $user, $pass, $db);

 // show errors (remove this line if on a live site)
 mysqli_report(MYSQLI_REPORT_ERROR);

表单php页面:

 <?php
 include("config_database.php")
  ?>


 <?php
 include("addproduct.php")
  ?>


<article>

  <section class="Input">

     <fieldset><legend><span> Add a product to the database </span></legend>


         <form action="addproduct.php" method="post">
          <label> product name: </label><input type="text" name="name"><br />
          <label> product quantity: </label><input type="text" name="quantity"><br />
          <label> product description: </label><input type="text" name="description"><br />                    
           <label> product price: </label><input type="text" name="price"><br />
           <input type="submit" class="reg">
           </form>

然后一个“addproduct.php”希望将数据发送到数据库:

   require_once ("config_database.php");

    if (isset($_POST['name']) &&
    !empty($_POST["name"]) &&


isset($_POST['quantity']) &&
    !empty($_POST["quantity"]) &&


isset($_POST['description']) &&
    !empty($_POST["description"]) &&


isset($_POST['price']) &&
    !empty($_POST["price"]))

 {
$name      = get_post('name');
$quantity    = get_post('quantity');
$description = get_post('description');
$price = get_post('price');



 $query = "INSERT INTO products VALUES" .
    "('', '$name', '$quantity', '$description', '$price')";


}
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}

如何将表单中输入的数据输入我的数据库?

1 个答案:

答案 0 :(得分:2)

您可以使用mysqli尝试这样的插入查询。

$query = "INSERT INTO products VALUES (NULL, '$name','$quantity', '$description','$price')";
$mysqli->query($query);

也可以使用像mysqli这样的真正的转义字符串。

$mysqli->real_escape_string($_POST[$var]);