php: PDO exception handling - php

I have two PHP files DBConnector.php
<?php
class DBConnector {
const DB_STRING = 'mysql:host=localhost;dbname=test';
const DB_USER = 'test';
const DB_PASSWORD = 'qwerty';
private $connection;
function __construct() {
$this->connection = new PDO(self::DB_STRING, self::DB_USER, self::DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function register_user($user_type, $login, $password, $email, $phone) {
$insert_user_sql = "insert into users (login, password, email, rating, phones, user_type)
values (:login, password(:password), :email, 0, :phone, :user_type)";
$sth = $this->connection->prepare($insert_user_sql);
$sth->execute(array(':login' => $login,
':password' => $password,
':email' => $email,
':phone' => $phone,
':user_type' => $user_type));
}
}
?>
and application.php
<?php
require "DBConnector.php";
require "UserType.php";
try {
$db = new DBConnector();
$db->register_user(UserType::OWNER, "test", "test", "test#gmail.com", "+111111111111");
} catch (Exception $e) {
echo "Error occured " + $e->getMessage();
}
?>
If the "insert into users" in DBConnector->register_user generates PDO exception, I can't catch it in my application.php.
Please, help me, what I'm doing wrong.

I found the problem.
The problem was in "plus" symbol, besides "." in echo command.
So "0" was printed, instead "Error occured..."

Related

why php-pdo don't insert values [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
I'm setting to do a simple query using PDO. However, when I run it, it does not insert. The database is called "famous" and the table is called "pessoas" containing only two columns called (codigo and nome).The connection works, but when I execute it return "Error to save".
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;bdname=pessoas';
$user = 'root';
$password = 'init4289';
try{
$pdo = new PDO($dsn, $user, $password);
echo 'SUCESSO AO CONECTAR!';
return $pdo;
}catch(PDOExeption $ex){
echo 'erro: '. $ex->getMessage();
}
}
?>
#end page "conexao_pdo.php"
<?php
include 'conexao_pdo.php';
$conn = getConnection();
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if($stmt->execute()){
echo 'Success to save';
}else{
echo '<p>'.'Error to save';
}
?>
You may consider the following:
probably it's just a typing error - bdname should be dbname in 'mysql:host=localhost;bdname=pessoas'
database and table names - 'famous' and 'pessoas' in the question, 'pessoas' and 'famous' in the code
include exception handling with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
your function getConnection() should return false on failure
Code, based on your question:
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;dbname=pessoas';
$user = 'root';
$password = 'init4289';
try {
$pdo = new PDO(
$dsn,
$user,
$password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
echo 'SUCESSO AO CONECTAR!';
} catch (PDOExeption $ex){
echo 'Error: '. $ex->getMessage();
return false;
}
return $pdo;
}
?>
<?php
include 'conexao_pdo.php';
// Connection
$conn = getConnection();
if ($conn === false) {
exit;
}
// Statement
try
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if ($stmt->execute()) {
echo 'Success to save';
} else {
echo '<p>'.'Error to save';
}
} catch (PDOExeption $ex){
die ('Error: '. $ex->getMessage());
}
?>

Using a function in php to create a database connection?

So really I just want to make stuff easier to read and just create a function where I can call upon the database connection, the below is what i've tried to do to do far.
So far, it doesn't work, it doesn't bring any message at all so presumably it isn't going into the try.
functions.php
function getDBConnection()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=name;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
}
catch(PDOException $e)
{
echo 'An error occured talking to the DB';
}
return $db;
}
and then do
submittest.php
require('functions.php');
getDBConnection(); //return $db
$username = 'donkey';
$password = 'donkey';
$email = 'donkey';
$county = 'donkey';
try
{
//Prepare and execute an insert into DB
$st = $db->prepare("INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:county)");
$st->execute(array(':username' => $username, ':password' => $password, ':email' => $email, ':county' => $county));
echo 'Success';
}
catch (PDOException $e)
{
echo 'An error occurred talking to the DB';
}
?>
$db = getDBConnection(); //return $db

PDO Insert Doesn't Throw Error or Insert Form Data

I am making the switch from MYSQL to PDO and on my form it will not insert the form data into the DB. What is strange is that it doesn't throw any errors but redirects to the success page without inserting the data. Here is my code:
<?php
session_start();
/*** mysql hostname ***/
$hostname = 'XXXXXXX.hostedresource.com';
/*** mysql username ***/
$username = 'XXXXXX';
/*** mysql password ***/
$password = 'XXXXXXXX';
try {
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
/*** echo a message saying we have connected ***/
//echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$loan_amount = trim($_POST['loan_amount']);
$loan_type = trim($_POST['loan_type']);
$debt_amount = trim($_POST['debt_amount']);
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$zip = trim($_POST['zip']);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try {
$sql="INSERT INTO leads (loan_amount, loan_type, debt_amount, first_name, last_name, email, phone, zip, reg_date) VALUES (:loan_amount, :loan_type, :debt_amount, :first_name, :last_name, :email, :phone, :zip, NOW())";
$statement = $pdo->prepare($sql);
$statement->bindValue(':loan_amount', $loan_amount);
$statement->bindValue(':loan_type', $loan_type);
$statement->bindValue(':debt_amount', $debt_amount);
$statement->bindValue(':first_name', $first_name);
$statement->bindValue(':last_name', $last_name);
$statement->bindValue(':email', $email);
$statement->bindValue(':phone', $phone);
$statement->bindValue(':zip', $zip);
$statement->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
exit();
}
header('Location: /success.php');
}
?>
The issue is with syntax:
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
You have a closing parenthesis and semi-colon at the end of your constructor which is breaking your code. You either need:
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password,
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
OR
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

PDO connection / prep and execute in there own functions best practice

Hi all i have been playing with PDO's and am slowly converting some old code over to this.
Getting a little stuck with a few thing and struggling to find what i need.
What i am getting stuck on is:
Having the $db in a function or the sorts so its only open when i
call it, i only want to manage one instance of this
checking if
execute was successful and if not return a value etc.
Also any advice on the below code would be great full as i have gathered this from sources around the web.
Current Code:
//Database Array
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'root');
//New PDO
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
//Check connection is ok
try {
$db->exec("SET CHARACTER SET utf8");
}
catch (PDOException $ex) {
print "Error!: " . $ex->getMessage() . "<br/>";
die();
}
//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $responce) {
$stmt = $db->prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, stamp_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
$stmt->execute();
print $db->lastInsertId();
$stmt = null;
}
//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst#test,com';
$offers = '1';
update($db, $fn, $ln, $email, $offers, $vlue, $responce);
thanks in advance for any help / tips
Edited Code:
//Database Array
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'local');
//New PDO
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Check connection is ok
try {
$db->exec("SET CHARACTER SET utf8");
}
catch (PDOException $ex) {
print "Error!: " . $ex->getMessage() . "<br/>";
die();
}
//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $responce)
{
$stmt = $db->prepare("insert into local (fName_765, lName_765, email_765, signup_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
try {
$stmt->execute();
print $db->lastInsertId(); //show ID
return true;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>"; // show error
return false;
}
}
//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst#test,com';
$offers = '1';
if (!update($db, $fn, $ln, $email, $offers, $vlue, $responce)) {
echo "no update there is a slight problem";
} else {
echo "it seemed to work";
}
Seem to be getting there, the above works hows it looking
checking if execute was successful and if not return a value etc.
Personally I prefer Exceptions, and PDO can be configured to raise Exceptions on errors. Exceptions are nice because the code that comes after the failed statement is not executed. This comes handy if you've a parent row, and then write some child rows which depend on the inserted parent. You don't want to write the child rows when the parent could not be created.
One can turn this on by doing this:
<?php
$pdo = new PDO(/* DSN */);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ATTR_ERRMODE_EXCEPTION);
Then you would do:
<?php
try {
$stmt->execute();
return true;
} catch (\PDOException $e) {
return false;
}
You can find more about this here: http://www.php.net/manual/en/pdo.error-handling.php
Having the $db in a function or the sorts so its only open when i call it, i only want to manage one instance of this
I'm usually managing a database connection by using a service container. The simplest existing option is Pimple. You then pass this service container around, and the service container is responsible for only creating one database connection.
<?php
$config = new \Pimple;
$config['db.options'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'root');
# Calling the "share" method makes sure that the function is only called when
# 'db' is retrieved the first time.
$config['db'] = $config->share(function() use ($config) {
return new PDO('mysql:host=' . $config['db.options']['host'] . ';dbname=' . $config['db.options'']['dbname'], $config['db.options'']['username'], $config['db.options'']['password']);
});
function update() {
global $config;
# Connection is only made the first time the 'db' key is accessed.
$db = $config['db'];
/* Do queries */
}
Having the $db in a function or the sorts so its only open when i call
it, i only want to manage one instance of this.
Open it at the start of your script and then pass it into the functions that need it. Opening a new database connection inside a function can lead to problems further down the line. For example, what if your function is used multiple times throughout the same script? You don't really want to open a new database connection every time that same function gets called.
checking if execute was successful and if not return a value etc.
As for checking if PDOStatement::execute was successful:
$result = $stmt->execute();
If you look at the manual, the return types are listed as:
Returns TRUE on success or FALSE on failure.
$result = $stmt->execute();
return $result;
or
return $stmt->execute();
Personally, I'd go with:
function update($db, $fn, $ln, $email, $offers, $vlue, $responce) {
$stmt = $db->prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, stamp_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
return $stmt->execute();
}
By the way, when you pass an object into a function, it is automatically passed by reference, which means that you can do something like:
$result = update($db, $fn, $ln, $email, $offers, $vlue, $responce);
if($result){
echo $db->lastInsertId();
}

Error in inserting data into database

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();
}

Categories