我的PDO插入数据不起作用

时间:2014-05-29 20:08:11

标签: php html pdo

我想要做的是在数据库的输入中添加我输入的数据,但我当前的代码不起作用。我从YouTube中观看的教程中获取了此代码。我的问题是它没有将我输入的数据添加到数据库中。

的index.php

<?php 
require_once('header.php');
?>
<html lang="en">
<head>
</head>
<body>
<form method="post" action="index.php"> 
Name: <input type="text" id="name" name="name" /><br />
Age: <input type="text" id="age" name="age" /><br />
Address: <input type="text" id="address" name="address" /><br />
<input type="radio" name="gender" id="gender" value="male" />Male
<input type="radio" name="gender" id="gender" value="Female" />Female<br />
<input type="submit" value="Add" />
</form>
</body>
</html>

的header.php:

<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";

$dbc = new PDO("mysql:host=" . $host . ";dbaname=" . $db, $user, $pass);

if(isset($_POST['name'])){
    $name = $_POST['name'];
    $age = $_POST['age'];
    $address = $_POST['address'];
    $gender = $_POST['gender'];
    $q = "INSERT INTO students(name, age, address, gender) VALUES(:name, :age, :address, :gender);";
    $query = $dbc->prepare($q);
    $results = $query->execute(array(
        ":name" => $name,
        ":age" => $age,
        ":address" => $address,
        ":gender" => $gender
    ));
}
?>

1 个答案:

答案 0 :(得分:1)

这里做了一些小清理。在;查询的末尾注意到现存的INSERT INTO,因此将其删除。此外,使用bindParam而不是传递数组。这应该有用。

if(isset($_POST['name'])){

    $name = isset($_POST['name']) ? $_POST['name'] : null;
    $age = isset($_POST['age']) ? $_POST['age'] : null;
    $address = isset($_POST['address']) ? $_POST['address'] : null;
    $gender = isset($_POST['gender']) ? $_POST['gender'] : null;

    $q = "INSERT INTO students(name, age, address, gender) VALUES(:name, :age, :address, :gender)";

    $query = $dbc->prepare($q);
    $query->bindParam(':name', $name);
    $query->bindParam(':age', $age);
    $query->bindParam(':address', $address);
    $query->bindParam(':gender', $gender);

    $results = $query->execute();

}

但是看看你的代码,有一些方法可以进一步改进它:

if(isset($_POST['name'])){

    $q = "INSERT INTO students(name, age, address, gender) VALUES(:name, :age, :address, :gender)";

    $query = $dbc->prepare($q);

    // Set an array of post values.
    $post_array = array('name','age','address','gender');

    // Loop through the post values, set the string & then assign the string via bindParam.
    foreach ($post_array as $post_value) {
      $$post_value = isset($_POST[$post_value]) ? $_POST[$post_value] : null;
      $query->bindParam(':' . $post_value, $post_value);
    }

    $results = $query->execute();

}

我做的主要改进是采用所有$_POST值和&amp;将它们放在一个数组中。然后循环遍历该数组并对值进行操作。