Why is this PDOException not caught? - php

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

Related

Connect and search the database then display that to a webpage?

I have some code that connects to a localhost MySQL server and displays if that database contains any matches of the search box. But I am now trying to connect to a SQL Server database and I just can't get it to work. Am I doing something wrong?
try {
$pdo = new PDO("sqlsrv:Server=xxx.xx.xx.xx,1433;Database=Live", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$stmt = $pdo->prepare("
SELECT *
FROM `dbo.Home`
WHERE `item_number` LIKE ? OR `stock_available` LIKE ?
");
$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]); <---LINE 54
$results = $stmt->fetchAll();
if (isset($_POST['ajax'])) { echo json_encode($results); }
I get the following error:
Connected successfully Fatal error: Uncaught PDOException:
SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Incorrect syntax near 'dbo.Home'. in
/usr/local/var/www/2-search.php:54 Stack trace: #0
/usr/local/var/www/2-search.php(54): PDOStatement->execute(Array) #1
/usr/local/var/www/1-form.php(14): require('/usr/local/var/...') #2
{main} thrown in /usr/local/var/www/2-search.php on line 54
Any help would be greatly appreciated.

MySQL error User has exceeded the 'max_questions' resource

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.

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

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