gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:10:37 24 4
gpt4 key购买 nike

这就是我正在尝试的方法:

数据库.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->("插入喊叫(姓名、消息、日期)值(:姓名、:消息、:日期)");

可能是什么原因导致的,以及如何使用 PDO 实际使用关联数组将数据插入 MySQL 数据库?

最佳答案

嗯...我可以看到一些缺陷:

数据库.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 教程和函数,以获取有关他们需要什么作为输入的更好信息。

关于php - 无法使用关联数组通过 PDO 插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30755830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com