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!');
Try this:
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;
}
}
}
The DatabaseCon should be acting as a factory to create your connection object.
Thanks to the help of #BenRowe, I found the issue and it is now fixed. A combination of using the $this keyword, and removing the "hello world!" portion from the call to bindParam() fixed it. Seems that the bindParam() method only takes a value based on reference. So I set a random variable $h to "hello world!," and changed bindParam(1, "hello world") to bindParam(1, $h).
Thanks everyone :)
Related
I'm trying to fetch data from a SQL Server database. After debugging, I could figure there's something wrong with the function.
Here's the code:
db.php
class Db{
public static function getConnection() {
$server='xxx';
$database='xxx';
$user='xxx';
$password='xxx';
$dsn="dblib:host=" . $server . ";dbname=" . $database;
try {
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e) {
echo 'SQL SERVER CONNECTION ERROR: ' . $e->getMessage();
}
return $conn;
}
}
functions.php
class Functions {
function getAcademicYear() {
$db = new Db();
$conn = $db->getConnection();
$conn->beginTransaction();
$sql = "SELECT academicYear FROM AcademicYear ORDER BY academicYearId DESC LIMIT 5";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn->commit();
echo $result;
} else {
$conn->rollback();
echo "false";
}
}
}
The function is returning false. Can you please review it and point out any mistakes?
I have the following code and whenever the function is called it is inserting the data twice.
The php that is calling the class/function:
$add_amenity = new listing;
echo $add_amenity->add_amenity($_POST['name']);
Here is the function:
public function add_amenity($a)
{
try {
$dbh = new PDO("mysql:host=" . db_host . ";dbname=" . db_name . "",db_user,db_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbh->prepare("INSERT INTO amenitylist (id,name,icon,isactive) VALUES ('',:a,'','1')");
$q->bindParam(':a', $a);
$q->execute();
$this->_results = $dbh->lastInsertId();
} catch(PDOException $e) {
$this->_results = "ERROR: " . $e->getMessage();
}
}
I know that error occurs usually when query returned false but this time this occurs with no reason! (or just I'm making a big mistake)
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?' AND `ticket_sender` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
if($getbaseticket === false){
return false;
}else{
$baseticket = $getbaseticket->fetch(PDO::FETCH_ASSOC);
}
I've theese lines in a function that returns support ticket information as array but as I said the error occurs when I tried to fetch the ticket information. I tried to check mysql errors just before fetch line by enabling the pdo debug mode and db->errorInfo() but it didn't work.
What can the problem be here?
Edit:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class TICKET_MANAGER
{
function __construct($dbhost, $dbname, $dbuser, $dbpass) {
try{
$this->db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Connection failed: ' . $e->getMessage() );
}
}
function viewTicket($ticket_safeid, $security_SenderId = false)
{
try{
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ? AND `ticket_sender` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
}catch(PDOException $e){
die('Mysql error: ' . $e->getMessage() );
}
...
}
...
}
It's the quotes around all your '?' - Remove them.
Read the manual
http://php.net/pdo.prepared-statements
from the manual:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
Exceptions should have told you that error
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
and used right after you've connected to your DB.
-http://php.net/manual/en/pdo.error-handling.php
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Query:
try {
// your query
}
catch(PDOException $e){
print $e->getMessage();
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I am VERY new to PHP / PDO, so please be gentle...
I am trying to enter code into my database and then fetch it into a webpage. I am able to do the first but am having difficulty displaying it. I am wondering if it's because i'm trying to combine $stmt and $handler together?
This is my code for entering the information into the database:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO survey (storename, receipt, date_visit)
VALUES (:storename, :receipt, :date_visit)");
$stmt->bindParam(':storename', $storename);
$stmt->bindParam(':receipt', $receipt);
$stmt->bindParam(':date_visit', $date_visit);
// insert a row
$storename = $_POST['storename'];
$receipt = $_POST['receipt'];
$date_visit = $_POST['date_visit'];
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
It works perfectly.
This is my code for fetching information from my database.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$handler->setAttribute(PDO::ATRR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class SurveyEntry {
public $id, $storename, $receipt, $date_visited,
$entry;
public function __construct() {
$this->entry = "{$this->storename} posted: {$this->receipt}";
}
}
$query = $handler->query('SELECT * FROM survey');
$query->setFetchMode(PDO::FETCH_CLASS, 'SurveyEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
I can confirm that it connects correctly, but I can't get it to display any information. I'm wondering if it's something to do with the difference in $stmt and $handler that i'm using? I've been following tutorials online and have quite possibly mixed 2 tutorials together to try and achieve what i'm looking for.
UPDATE:
I managed to get it to work by updating how I called from the database:
$host = "localhost";
$dbname = "test";
$user = "test";
$password = "test";
$handler = new PDO( "mysql:dbname=$dbname;host=$host" , $user , $password );
Figured it out - I had 'ATRR_ERRMODE' instead of 'ATTR_ERRMODE' (typo)
how are you?
You should try to fix it:
1- Two different connections:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
When I try to run this code it will not insert the data into the database?
<?php
class Database {
private $dsn;
function __construct($dbname, $host, $user, $password, $enckey) {
$this->dsn = "mysql:dbname=" . $dbname . ';host=' . $host;
$this->user = $user;
$this->password = $password;
}
private function createDSN() {
return $this->dsn;
}
public function createConnection() {
try {
$dbh = new PDO(self::createDSN(), $this->user, $this->password);
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
}
$db = new Database('mytest', 'localhost', 'root', 'hashedpassword', null);
$dbh = $db->createConnection();
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
?>
I don't get an error message
but you have to get it. Asking other people about your database makes very little sense.
Asking the database itself is a way better idea.
add this line to your createConnection() (I dunno what this function for but as you have it)
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
and run your code this way
try {
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
} catch (PDOException $e) {
echo $e->getMessage();
}