How can I check PDO connection? - php

Here is my code:
<?php
try{
// connect to database and select database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "spy";
$dbh_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh_conn->exec("set names utf8");
$dbh_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
My code works as well. But I seen a similar code which checks the connection like this:
if ( !$dbh_conn ){
// Something Went Wrong
} else {
// All Fine
}
Well do I need to this ^ condition? Or using try catch is enough to check db connection?

It depends on what you set for PDO::ATTR_ERRMODE. In your case, it's set as PDO::ERRMODE_EXCEPTION, so an error will throw an Exception.
$dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
This error mode however is not applied when you connect (i.e., when __constructor() is called in PDO), since a PDOException is always thrown:
PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.
You can read about the different modes here.

Related

Why is my catch exception code not working?

I can connect the database and the PHP but if I intentionally mess up the database, it doesn't do the code for the catch. The catch is not working. It only displays the warning. I would also like to know how to get rid of that.
This is the warning I get:
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'mytodsssssasdsdasdassdos' in D:\XAMPP\htdocs\projects\index.php on line 10
What am I doing wrong?
Here is my PHP code
<?php
$user = 'root';
$password = '';
$db = 'mytodsssssasdsdasdassdos'; //real DB name is mytodos
try {
$db = new mysqli('localhost', $user, $password, $db);
} catch (mysqli_sql_exception $e) {
die (var_dump('Unable to Connect to the Database.'));
} //echo 'Connected.';
By default error reporting for mysqli is disabled. The only "error" you ever get is the warning when the connection can't be established. You can't catch warnings in PHP with try-catch. However, there is a very simple solution. Enable error reporting properly and you will be able to catch all mysqli errors.
try {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', $user, $password, $db);
} catch (mysqli_sql_exception $e) {
// Do something with the exception here and rethrow it.
throw $e;
}
On the unrelated note, it doesn't look like you need to catch anything there. Just stick to the standard way of connecting without any catching:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', $user, $password, $db);
$db->set_charset('utf8mb4');

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

PDO MySQL connection troubleshooting

I'm running the following very basic PDO:MySql connection:
<?php
$host = '127.0.0.1:8888';
$db = 'communities';
$user = 'root';
$pass = 'yY5MF)q/DCzc';
// Create connection
try {
$conn = new PDO('mysqli:host=$host;dbname=$db', $user, $pass);
foreach($conn->query('SELECT * from city_detail') as $row) {
print_r($row);
}
$conn = null;
// Check connection
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
echo "Connected successfully";
?>
I've modified php.ini to allow for extension=php_pdo_mysql.dll with no effect. Is there something else that I'm missing. I am using PHP7.0.3. The error message output is Error!: could not find driver Kudos!
You need to use double quotes to get variable data inside string:
$conn = new PDO("mysqli:host=$host;dbname=$db", $user, $pass);
The problem was using msqli instead of mysql.

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

Very Confusing PDO php exec() connection issue

I have run into a very confusing issue with connecting to a database via PHP PDO using exec().
I have thrown together the following snippet to illustrate my point.
$host = "localhost";
$db_name = "some_db";
$user_name = "some_user";
$pass_word = "some_password";
try {
// assign PDO object to db variable
$dbh = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $user_name, $pass_word, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
echo "yahoo connected";
}
catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error: " . $e->getMessage();
}
When I run this code via the browser it connects fine but when I run it at the command line it gives the following error:
Connection Error: SQLSTATE[28000] [1045] Access denied for user 'some_user'#'localhost' (using password: NO)
Needless to say that this is confusing as the password is indeed set as you can see in the code above and the connection works and prints yahoo to the screen in the browser. Any ideas are appreciated.
Your snippet is wrong. It ought to be without useless try-catch block:
$host = "localhost";
$db_name = "some_db";
$user_name = "some_user";
$pass_word = "some_password";
$dsn = "mysql:host=$host;dbname=$db_name;charset=utf8"
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
// other options
);
$dbh = new PDO($dsn, $user_name, $pass_word, $opt);
echo "yahoo connected";
this way you will get a complete error message,including stack trace which will show you the actual file you runs - in which there is empty password used.
it is also important to have error_reporting(E_ALL); to tell you possible issues with variables scope

Categories