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(...
Related
I have this little snippet that connects to sql server using PDO, and it fails because my server is down (which is correct, it's the scenario I want to test). However, the exception is not caught!
$dsn = "sqlsrv:Server=$host,$port;Database=$database";
$conn = new PDO($dsn, $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$works = false;
try {
$works = ($conn->exec('SELECT * FROM INFORMATION_SCHEMA.TABLES') !== false);
}
catch (\PDOException $e) {
}
echo "works? " . ($works ? 'yes' : 'no') . "\n";
The output I get in console:
➜ backend git:(dev) ✗ php mssql-pdo-test.php
PHP Fatal error: Uncaught PDOException: SQLSTATE[HYT00]: [Microsoft][ODBC Driver 17 for SQL Server]Login
timeout expired in /path/mssql-pdo-test.php:10
Stack trace:
#0 /path/mssql-pdo-test.php(10): PDO->__construct()
#1 {main}
thrown in /path/mssql-pdo-test.php on line 10
I guess the exception is thrown outside the try / catch block here:
$conn = new PDO($dsn, $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
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');
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.
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1226
User 'bb99ddb719cd2f' has exceeded the 'max_questions' resource
(current value: 3600) in execute().
Earlier code was working file but suddenly it has started giving errors at every execute().
Here is my code:
Actual file:
<?php
$sql="SELECT count(job_status.is_approved) as is_approved
from job_status
WHERE job_status.job_id=:job_id and job_status.is_approved=1";
$sth=$conn->prepare($sql);
$sth->bindValue("job_id",$job_id);
try {
$sth->execute();
}
catch(Exception $e) {
Rollbar::report_exception($e);
}
$res=$sth->fetchAll();
$stats=$res[0]['is_approved'];
$status=$stats?'1':'0';
return $status;
Db connection file:
<?php
require_once('config.php');
try {
$dsn = "mysql:host=$DB_HOST;dbname=$DB_DATABASE";
$conn = new PDO($dsn, $DB_USER, $DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET NAMES 'utf8'");
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Some servers have query limit same is the case with heroku in cleardb i.e., 3600 QPH. So to resolve this issue we bought the paid version of cleardb to extend the query limit.
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();
}
?>