PHP PDO connection problem

I’m learning PHP PDO and at the moment I can connect to my database using the traditional mysql_connect() function but not the using the PHP PDO way.

Here here goes the code using the mysql_connect() function.


<?php

echo 'This is a test';

/*
database name onetwo_test1
database onetwo_test1 username onetwo_test1u1 with password dbpw123
*/

$host = 'localhost';
$username = 'onetwo_test1u1';
$password = 'dbpw123';
$dbname = 'onetwo_test1';

$conn = mysql_connect($host, $username, $password) or die('Could not connect: ' . mysql_error());

?>

Here goes the code using the PHP PDO way, and yes I know that I should use a try and catch.


<?php

echo 'This is a test';

/*
database name onetwo_test1
database onetwo_test1 username onetwo_test1u1 with password dbpw123
*/

$host = 'localhost';
$username = 'onetwo_test1u1';
$password = 'dbpw123';
$dbname = 'onetwo_test1';

$conn = new PDO('mysql:host=localhost;dbname=$dbname', $username, $password);
?>

Thanks

Hi,

You need to double-quote your connection string, otherwise PHP won’t replace $dbname with the actual value:

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);

That didn’t work either.

Here goes the code again and the error code that is being shown on the page.


<?php

echo "This is yet another test <br />";

$host = 'localhost';
$username = 'onetwo_test1u1';
$password = 'dbpw123';
$dbname = 'onetwo_test1';

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
?>


This is yet another test 

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000] [1044] Access denied for user 'onetwo_test1u1'@'localhost' to database 'onetwo_test1'' in /home/onetwo/public_html/samplesite.com/test/test/test5.php:23 Stack trace: #0 /home/onetwo/public_html/samplesite.com/test/test/test5.php(23): PDO->__construct('mysql:host=loca...', 'onetwo_test1u1', 'dbpw123') #1 {main} thrown in /home/onetwo/public_html/samplesite.com/test/test/test5.php on line 23

That error means the specified user does not have access to the database.

Running the below within MySQL from the command prompt should fix the problem.


GRANT ALL ON onetwo_test1.* TO 'onetwo_test1u1'@'localhost';

Though before you run that double check that the username, database name and password are correct in the script. If those things are all correct than the *likely cause is that the user does not have access to the database itself.

Thanks. It worked. When I created a new database and user for testing purposes, I completely forgot to assign the user to the database. I went to my cpanel to fix this.

Thanks a lot!