The problem is caused by 2 syntax errors in your Data Source Name (DSN) (the first argument in the PDO connection string).
The errors
- You cannot pass your db constant into the connection string as
"...dbname = db"
. Since db
is wrapped in double quotes and will be interpretted as a string instead of a constant.
You cannot have spaces in your DSN. It should be:
"mysql:host=localhost;dbname=login_db" //no spaces.
I've tested this and it exhibits some strange behaviour:
- Specifically, it seems that the space between
host
and the first =
sign causes the problem. If there is a space, it will echo "You are connected"
even if "localhost" is misspelled.
- Similarly, if there is a space between
dbname
and its =
sign, it will appear to connect even if the specified database name is incorrect.
My guess is that this is some quirk of how the PDO class parses the DSN.
The solution
Remove all the spaces from the DSN.
You also need to pass in your database name in a different way. There are different ways to fix this. I would recommend, for the sake of not getting any more weird-to-debug-errors, that you use variables instead of constant definitions:
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'login_db';
try{
$dbh = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
echo "You are connected";
}
catch(PDOException $e){
echo $e -> getMessage();
}
As for good tutorials, you can look at these:
Net.tuts+ : PHP Database Access
Net.tuts+ : Why use PDOs
And of course the don't forget the php.net docs.
php.net : PDOs