我正在玩PDO,但有些奇怪的事情正在发生,我似乎无法弄明白。没有错误产生。只是没有插入数据库。
的index.php
<?php
error_reporting(E_ALL);
require('includes/classes.php');
require_once('includes/config.php');
$db = new DatabaseCon();
$db->dbConnect($config);
$stmt = $db->prepare("INSERT INTO images (filename) VALUES (?)");
$stmt->bindParam(1, "hello world!");
$stmt->execute();
?>
classes.php
<?php
error_reporting(E_ALL);
require('config.php');
// Connect to database
// Does not handle anything else
class DatabaseCon {
public $dbh;
// Method to connect to database
function dbConnect($config) {
try {
$dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
的config.php
<?php
error_reporting(E_ALL);
$config = array(
'host' => 'localhost', // Database hostname (usually localhost)
'dbuser' => 'admin_mp', // Database username
'dbpass' => 'mypassword here', // Database password
'dbname' => 'mpdb' // Database name
);
当我导航到index.php时,应该将“hello world”插入到数据库中,但事实并非如此。谁能找到我在这里做错了什么?
答案 0 :(得分:2)
更改
$dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
到
$this->dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
更改
$stmt = $db->execute("INSERT INTO images (filename) VALUES (?)");
$stmt->bindParam(1, "hello world!");
$stmt->execute();
到
error_reporting(E_ALL);
$stmt = $db->dbh->prepare("INSERT INTO images (filename) VALUES (?)");
if (!$stmt) die ('prepare() failed!');
$h = "hello world!";
$rv = $stmt->bindParam(1, $h);
if (!$rv) die ('bindParam() failed!');
$rv = $stmt->execute();
if (!$rv) die ('execute() failed!');
答案 1 :(得分:1)
试试这个:
<强>的index.php 强>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require('includes/classes.php');
require_once('includes/config.php');
$db = new DatabaseCon();
$db = $db->dbConnect($config);
$stmt = $db->prepare("INSERT INTO images (filename) VALUES (?)");
$stmt->bindParam(1, "hello world!");
$stmt->execute();
?>
<强> classes.php 强>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require('config.php');
// Connect to database
// Does not handle anything else
class DatabaseCon {
// Method to connect to database
function dbConnect($config) {
try {
$dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
return $dbh;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
}
DatabaseCon应该充当工厂来创建连接对象。
答案 2 :(得分:0)
感谢@BenRowe的帮助,我找到了问题,现在已修复。结合使用$ this关键字,删除“hello world!”调用bindParam()的部分修复了它。似乎bindParam()方法只接受基于引用的值。所以我将随机变量$ h设置为“hello world!”,并将bindParam(1,“hello world”)更改为bindParam(1,$ h)。
谢谢大家:)