Catch exception when on PDO connection - php

I have the following connection being made using PDO. Obviously it won't connect as I've not specified host or database (or user or password)
$dbh = new PDO('mysql:host=;dbname=', '', '');
..so how do I catch the exception? I'm trying something like this:
try {
$dbh = new PDO('mysql:host=;dbname=', '', '');
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
}
.. but no message is displayed. Why?

Are you using custom namespace? then you need to change
} catch (\Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
}
notice the backslash before Exception.

You need to pass the attribute ERRMODE_EXCEPTION in order to receive exceptions on a failing connection attempt:
$dbh = new PDO('mysql:host=;dbname=', '', '', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
Check the manual page of PDO::__construct() for more info.
Please also check #Ali's answer!

Related

PDO database connection issue in MAMP – Keeps creating new databases

For some reason, this code always returns “Connected to Database” even when I try to test the, try catch block and break the connection. When I change the name of the database to test the exception, it just creates a new database.
Any ideas?
<?php
try{
$db = new PDO ("sqlite:".__DIR__."/database.db");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage();
exit;
}
echo "Connected to Database";
?>
I believe this is expected behavior with pdo_sqlite: if you provide a path to a database that doesn't exist, and PHP is able to write to files in the directory of that path, it will simply create the database under the filename you've provided.
If you want to test the case where the file isn't writable, you can change file permissions such that the user that PHP runs as doesn't have write access.
Because echo "Connected to Database"; is not within the try brackets, it will always echo that.
Try this.
<?php
try{
$db = new PDO ("sqlite:".__DIR__."/database.db");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connected to Database";
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage();
exit;
}
?>

Invalid data source names - PDO

So I've had this code running for PDO connection to my database.
Since last couple of hours, I'm getting a weird error called "invalid data source name".
I've searched quite a bit but I'm getting no solutions for it. What might be the reason?
Connection Code
<?php
$connectionString = 'mysqlhost=127.0.0.1;dbname=cdm';
try
{
$conn = new PDO($connectionString, 'root', 'PASS1234');
$conn->setAttribute(PDOATTR_ERRMODE, PDOERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
var_dump($conn);
?>
Output
invalid data source nameNULL
Your entire code is totally wrong.
first fix :
$connectionString = 'mysqlhost=127.0.0.1;dbname=cdm'; to $connectionString = 'mysql:host=127.0.0.1;dbname=dgsa';
Then change the following :
$conn->setAttribute(PDOATTR_ERRMODE, PDOERRMODE_EXCEPTION);
To :
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Full correct code :
<?php
$connectionString = 'mysql:host=127.0.0.1;dbname=dgsa';
try
{
$conn = new PDO($connectionString, 'root', 'PASS1234');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
var_dump($conn);
?>
I think you need to change the variable to this :
$connectionString = 'mysql:host=127.0.0.1;dbname=cdm';
I think it's just a typo
$connectionString = 'mysqlhost=127.0.0.1;dbname=cdm';
should be
$connectionString = 'mysql:host=127.0.0.1;dbname=cdm'; ( with : )

My file corrupt when using db connection

I have a download script which get id of file and search in database and find it's name. But when I include my db connection the files get corrupted on download.
when I comment my db connection and give file name manually file downloading work fine.
I test my db connection and there wasn't any excpetion or any html output , what do you think my problem is?
<?php
session_start();
try{
$db= new PDO("mysql:host=localhost;dbname=dbname","user","pass");
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$db->exec("SET NAMES 'utf8'");
}catch (Exception $e){
//echo "something wrong in db.php";
echo $e->getMessage();
exit;
}
?>
I run my code on windows server IIS, if it does matter
Just try with this code..
error_reporting(E_ALL);
ini_set('display_errors','1');
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
It will return your error.
after few days struggling and headache finaly problem resolved by deleting try catch block

PHP/PDO - Server has gone away and Exceptions

I am attempting to make a php + pdo website that has persistent connections. Of course, the connections are closed every 8 hours of inactivity so I am attempting to create a php file that reopens the connection if it is closed
Here is my code:
try{
$db = new PDO("mysql:host=$database_ip;dbname=$database_name", $database_username, $database_password, array(PDO::ATTR_PERSISTENT => true));
}catch(Exception $x){
try{
$db = new PDO("mysql:host=$database_ip;dbname=$database_name", $database_username, $database_password);
}catch(Exception $x){
echo 'Failed database error';
}
}
This says that "PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal."
The problem is that even though the exception is caught it is still fatal :/
Here's the error:
Warning: PDO::__construct(): MySQL server has gone away in /path/to/website/mysql.inc.php on line 3
First of all you should catch PDOException
Second you are already trying to reconnect so set ATTR_PERSISTENT to FALSE.
try{
$db = new PDO( '...' ); // array(PDO::ATTR_PERSISTENT => FALSE)
}catch(PDOException $x){
echo 'Caught exception: ', $x->getMessage(), "\n";
try{
//reconnect
$db = new PDO( '...' );
}catch(PDOException $e){
throw new Exception('Failed database error'.$e->getMessage());
}
}
the # operator suppresses the warning:
$db = #new PDO(...

connection to the database using PDO

im trying to learn PDO
i've made this code to connect to the database
<?php
$dbhost = "localhost";
$dbname = "testcreate";
$dbuser = "root";
$dbpass = "mysql";
if (!$db) {
throw new Exception('failed to connect to mysql')
}
try {
$db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname.';charset=utf8', ''.$dbuser.'', ''.$dbpass.'');
} catch (MyFunkyException $e) {
echo "Caught exception : ", $e->getMessage();
}
?>
the connection works, but when i try to make an error and i want to catch the error
this error popup
Fatal error: Uncaught exception 'Exception' with message 'failed to connect to mysql' in C:\Program Files (x86)\Ampps\www\test.php:8 Stack trace: #0 {main} thrown in C:\Program Files (x86)\Ampps\www\test.php on line 8
can you help me fix the error or shows me the right way to do it
the problem is that
You're trying to throw exception before connection and outside of try.
There is no need to throw your own exception because PDO throws its own exception if connection fails.
Also you'd consider exception type.
try {
$db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname.';charset=utf8', ''.$dbuser.'', ''.$dbpass.'');
} catch (PDOException $e) {
echo "Caught exception : ", $e->getMessage();
}
Also, there is no need to turn PDO on exceptions to catch an exception. But if you are trying to handle errors with exceptions you must turn on that feature right after connection is established.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The problem is that you don't want to catch anything.
At least until you want it only to echo the error message out.
Also, exceptions has nothing to do with PDO syntax.
The real problem here is in this line:
} catch (MyFunkyException $e) {
MyFunkyException is a classname of the type of exception you want to catch.
PDO doesn't throw a MyFunkyException exception - the docs state that it throws a PDOException exception.
You can fix this by changing the line like this:
} catch (PDOException $e) {
Or by catching all exceptions regardless of type, like this:
} catch (Exception $e) {
try by using this code below
<?php
$dbhost = "localhost";
$dbname = "testcreate";
$dbuser = "root";
$dbpass = "mysql";
try {
$db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname.';charset=utf8', $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>

Categories