在PDO调用中使用PHP CONSTANTS

前端之家收集整理的这篇文章主要介绍了在PDO调用中使用PHP CONSTANTS前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<?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);

    $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.”

我已经“谷歌搜索”并在此处找到了部分答案.所以我希望在这里完成.

TIA

你做:
$DBH = new PDO("MysqL:host=localhost; dbname= sitename",root);

应该是:

$DBH = new PDO("MysqL:host=localhost; dbname= sitename",'root','root');

有报价.否则PHP认为它是一些常量而不是字符串.但是通过查看你的代码,我发现你已经定义了常量来访问数据库,所以你为什么不这样做呢:

$DBH = new PDO('MysqL:host='.DB_HOST.'; dbname='.DB_NAME,DB_USER,DB_PASSWORD);

UPDATE

我也看到你正在使用MysqL与PDO.请注意,为了safely use MySQL with PDO你需要disable emulated prepared statements

$DBH = new PDO('MysqL:host='.DB_HOST.'; dbname='.DB_NAME.';charset=utf8',DB_PASSWORD);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);

请注意,我还在DSN字符串中设置了编码(在我的情况下为utf8).我也想知道你的代码中是否真的需要常量,因为通常每个请求只需要一个连接(到同一个数据库),因此如果只创建一次连接并通过,则不需要让这些全局变量浮动与需要它的代码部分的连接.有关此内容的更多信息,请参阅我的related question.

猜你在找的PHP相关文章