<?php # Nettuts Tutorial using PHP Data Objects (PDO),
/**This file contains the database access information
*This file also establishes a connection to mySQL
*and selects the database.
*Set the database access information as constants:
**/
// print_r(PDO::getAvailableDrivers());
DEFINE('DB_USER', 'root');
DEFINE('DB_PASSWORD', 'root');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'sitename');
$php = "htmlspecialchars";
try {
#MySQL with PDO_MYSQL
// $DBH = new PDO("mysql:host={$php(DB_HOST)}; dbname={$php(DB_NAME)}", root, root};
$DBH = new PDO("mysql:host=localhost; dbname= sitename", root, root);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# UH-OH! Typed DELECT instead of SELECT!
$DBH->prepare('DELECT name FROM people');
} catch (PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
?>
The Console in OS X returns “[14-Aug-2011 15:59:59] PHP Notice: Use
of undefined constant root – assumed ‘root’ in
/Applications/MAMP/htdocs3/nettuts/PHP/PDO for Database
Access/mysql_pdo_connect.php on line 20.”
I’ve “googled” and found a partial answer here. So I was hoping for completion here.
TIA
You do:
Which should have been:
With quotes. Otherwise PHP thinks it is some constant instead of a string. However by looking at your code I see you have defined
constantsto access the database so why don’t you simply do:UPDATE
I also see that you are using MySQL with PDO. Please note that in order to safely use MySQL with PDO you have to disable emulated prepared statements:
Please note that I have also set the encoding in the DSN string (in my case to utf8). I also wonder if you really need the constants in your code, because often you will only need one connection per request (to the same database) so you don’t need to have those globals floating around if you just create the connection once and pass the connection to the parts of the code that need it. See also my somewhat related question for more information about this.