connection to the database using PDO - php

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

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');

How can I check PDO connection?

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.

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

PDOException not being caught?

I'm getting the following error in PHP:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'localhost' (10061)' in C:\xampp\htdocs\project\Service\Database.class.php:26 Stack trace: #0 C:\xampp\htdocs\project\Service\Database.class.php(26): PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 C:\xampp\htdocs\project\Service\Database.class.php(54): Service\Database::initialize() #2 C:\xampp\htdocs\project\index.php(15): Service\Database::getHandler() #3 {main} thrown in C:\xampp\htdocs\project\Service\Database.class.php on line 26
The error itself is not the problem, I intentionally terminated the MySQL service in Windows to see what happened (I'm using XAMPP). The problem is that I'm unable to catch the exception that the PDO object throws and I don't know why.
try {
$host = "localhost";
$dbname = "project";
$userName = "root";
$password = "";
$charset = "utf8";
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
);
// This is the line that supposedly throws the exception (LINE 26):
$dbh = new PDO($dsn, $userName, $password, $driverOptions);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::setHandler($dbh);
} catch (PDOException $e) {
die("CATCHED"); // This line is never reached
} catch (Exception $e) {
die("CATCHED"); // nor this one.
}
What am I missing here?
The only thing I can think of is if you're inside a namespaced class, and should use \PDOException instead of PDOException.
Turn on error_reporting and check the errors.
ini_set('display_errors', true);
error_reporting(E_ALL);
May be there is a fatal error, before that line, or maybe PDO is not available.

Categories