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.
Related
I have made numerous attempts, most returning the odd error of 'could not find driver' when using PDO. I've confirmed multiple times with customer support that my credentials are correct. I've gone over the code looking for bugs, and found none. I built some simple tests, two examples below, one returning the error of 'Call to undefined function mysqli_connect()', the other returning the aforementioned ''could not find driver'.
I've been reading and googling and have yet to find a solution which is able to provide a working connection. Hoping for guidance on how to proceed
test 1: produces 'driver not found' error
$host = 'notmyHOST';
$db = 'notmyDATABASE';
$password = 'notmyPASSWORD';
$user = 'notmyUSERNAME';
$dsn = "mysqli:host=$host;dbname=$db;charset=UTF8";
try {
$pdo = new PDO($dsn, $user, $password);
if ($pdo) {echo "Connected to the $db database successfully!";}
} catch (PDOException $e) {
echo $e->getMessage();
}
//test 2: produces 'driver not found' error
//This test is a straight line-for-line copy of the example connect code
//provided by Dreamhosts knowledge-base
$hostname = "mysql.example.com"; //hostname created when creating the database
$username = "yourusername"; //username specified for database
$password = "yourpassword"; //password specified for database access
$database = "databasename"; //database name specified at creation
$link = mysqli_connect($hostname, $username, $password, $database);
if (mysqli_connect_errno()) {
die("Connect failed: %s\n" + mysqli_connect_error());
exit();
}
/*
test 3: produces 'Fatal error: Uncaught Error: Class "mysqli" not found in
/home/*****/*****/a___connectTEST4.php:25 Stack trace: #0 {main} thrown in
/home/*****/*****/a___connectTEST4.php on line 25' error
*/
$hostname = 'myHOST';
$database = 'myDATABASE';
$password = 'myPASSWORDS';
$username = 'myUSERNAME';
// Create connection
$conn = new mysqli($hostname, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
To recap, I'mooking for advice/solution/how to proceed to resolve connection error in any of the tests provided. In all tests I checked all credentials multiple times, they are correct; Haven't found a solution which maps to my problem on Stack Overflow, but I've looked at similar issues without success.
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't get mysql table to load on localhost. below i used PDO and the table worked fine. no errors...the table works fine in phpmyAdmin...please help driving me nuts. i imported table from my web server to local host from a earlier version..
<?php
$user = "root";
$pass = "root";
try {
$dbh = new PDO('mysql:host=localhost;dbname=iosLeads',$user,$pass);
foreach($dbh->query('SELECT * from Customer') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error! :" . $e->getMessage()."<br/>";
die();
}
?>
but when i used this code it show a blank screen, no errors..i tried same code with other tables and it works fine.
<?php
// set up the connection variables
$db_name = 'iosLeads';
$hostname = 'localhost';
$username = 'root';
$password = 'root';
// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
// a query get all the records from the users table
$sql = 'SELECT * FROM Customer';
// use prepared statements, even if not strictly required is good practice
$stmt = $dbh->prepare( $sql );
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
// convert to json
$json = json_encode( $result );
// echo the json string
echo $json;
?>
I'm getting this in my php error.log
[17-Dec-2014 03:39:55 Europe/Berlin] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:8888' (20)' in /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php:10
Stack trace:
0 /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php(10): PDO->__construct('mysql:host=loca...', 'root', 'root')
1 {main}
thrown in /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php on line 10
[17-Dec-2014 03:40:00 Europe/Berlin] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:8888' (20)' in /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php:10
Stack trace:
0 /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php(10): PDO->__construct('mysql:host=loca...', 'root', 'root')
1 {main}
thrown in /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php on line 10
[17-Dec-2014 03:40:23 Europe/Berlin] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:8888' (20)' in /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php:10
Stack trace:
0 /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php(10): PDO->__construct('mysql:host=loca...', 'root', 'root')
1 {main}
thrown in /Applications/MAMP/htdocs/iosLeads/iosCustomerError.php on line 10
If the array in $result has strings other than UTF-8 encoded, the function json_encode() may fail and will return false (see PHP manual json_encode). To check this, dump the value of $result before using json_encode():
var_dump($result);
If you have an array in $result but no other return value than false from json_encode(), you must set the correct character encoding for the database connection.
this is my code it's working in local host but not in server
$dbtype = 'mysql'; // Normally mysql
$host = 'localhost'; // This is normally set to localhost
$db_username = 'name'; // DB username
$db_password = 'pass'; // DB password
$db_name = 'db_name'; // DB database name
$dbprefix = 'db_'; // Do not change unless you need to!
$cat_table="db_cat";
try
{
$pdo = new PDO('mysql:host='. $host .';port=2082;dbname='.$db_name, $db_username, $db_password);
}
catch (PDOException $e)
{
die($e);
}
?>
ERROR MESSAGE
exception 'PDOException' with message 'SQLSTATE[HY000] [2000] mysqlnd cannot connect to
MySQL 4.1+ using the old insecure authentication. Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password').
This will store a new, and more secure, hash value in mysql.user. If this user is used in
other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords flag
from your my.cnf file' in /home/jeywigki/public_html/hotel/db/config.php:13 Stack trace:
#0 /home/jeywigki/public_html/hotel/db/config.php(13): PDO-
>__construct('mysql:host=loca...', 'table', 'pass') #1 /home/jeywigki/public_html/hotel/index.php(3): require_once('/home/jeywigki/...') #2 {main}
kindly help me.
thanks in advance
I am not sure but it could be the issue.
you can try this:
mysql:host=$host;dbname=$db_name inside in quotes.
try
{
$pdo = new PDO("mysql:host=$host;dbname=$db_name", $db_username, $db_password);
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
docs
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();
}
?>