I am playing around with PDO, but something weird is happening that I cannot seem to figure out. There are no errors being produced. Just nothing being inserted into the database.
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
);
When I navigate to index.php, "hello world" should be inserted into the database, but it's not. Can anyone find what I am doing wrong here?
Change
$dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
to
$this->dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
Change
$stmt = $db->execute("INSERT INTO images (filename) VALUES (?)");
$stmt->bindParam(1, "hello world!");
$stmt->execute();
to
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!');