无法使用关联数组通过PDO插入数据

时间:2015-06-10 12:04:58

标签: php mysql pdo

我是怎么做的:

database.php中:

<?php

    $host = "host";
    $user = "user";
    $pass = "password";
    $dbname = "database";

    try {
        # MySQL with PDO_MYSQL
        $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
        $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }

    ?>

必须插入数据的文件:

<?php 
include 'database.php'; 
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';

var_dump($_POST);

if(isset($_POST['name']) && isset($_POST['message'])){
    $data = array( 
        'name' => $_POST['name'], 
        'shout' => $_POST['message'], 
        'date' => $_POST['date']
    );

    $STH->bindParam(':name', $_POST['name']);
    $STH->bindParam(':message', $_POST['message']);
    $STH->bindParam(':date', $_POST['date']);

    try {
        $STH = $DBH->prepare("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");
        $STH->execute($data);
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
}

?>

根据这个http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059,它应该接受关联数组。但它没有做任何事情并说我在这一行中有错误:

$STH = $DBH->("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");

可能导致它的原因,以及我如何使用关联数组使用PDO将数据插入MySQL数据库?

1 个答案:

答案 0 :(得分:1)

嗯......我可以看到一些瑕疵:

<强> database.php中     

$host = "us-cdbrbababababableardb.net";
$user = "b9bababababefc";
$pass = "9c4ababab";
$dbname = "heroku_aabababab49";
$DBH = null;

try {
    # MySQL with PDO_MYSQL
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

}
catch(PDOException $e) {
    echo $e->getMessage();
}

?>

必须插入数据的文件

<?php 
include 'database.php'; 
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';

var_dump($_POST);

if(isset($_POST['name']) && isset($_POST['message'])){
    $data = array( 
        'name' => $_POST['name'], 
        'shout' => $_POST['message'], 
        'date' => $_POST['date']
    );

    try {
        // NOTICE: prepare() used and VALUES instead of VALUE
        $STH = $DBH->prepare("INSERT INTO shouts (name, message, date) values (:name, :message, :date)");

        $STH->bindParam(':name', $_POST['name']);
        $STH->bindParam(':message', $_POST['message']);
        $STH->bindParam(':date', $_POST['date']);

        // NOTICE: $data has allready been supplied by bindParam()
        $STH->execute();
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
}

?>

这些只是我在代码中发现错误的第一件事...尝试阅读PDO教程和函数,以获得有关他们需要输入的更多信息。