我在使用PDO連接中的常量以及調用包含PDO連接的函數時遇到問題。在PDO連接字符串中使用常量並使用PDO連接調用函數
我正在使用函數僅在需要時連接數據庫。在不需要數據庫工作的頁面上,不需要連接。
我試了很多,但不能確定我要去哪裏錯了。
<?php
/** The name of the database */
define('DB_NAME', 'dev-db');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'dxdb');
/** MySQL hostname */
define('DB_HOST', 'localhost');
function connect(){
try
{**//Here's where the first problem is**
$conn = new PDO('mysql:host=DB_HOST;dbname=DB_NAME',DB_USER,DB_PASSWORD);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}
connect();// Here's where it fails again
$sql = 'insert into names (names) values (:what)';
$what = "testValue";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':what', $what, PDO::PARAM_STR, 5);
$stmt->execute();
你要串聯這樣的'$康恩=新PDO(「mysql的字符串: host ='。DB_HOST。'; dbname ='.DB_NAME。',DB_USER,DB_PASSWORD);' – HamZa 2013-04-23 08:20:42
哦!舊的東西不需要連接''$ link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);''所以我認爲它在這裏是一樣的。 – Norman 2013-04-23 08:22:26
那麼,PHP會如何判斷'echo'DB_HOST';'是一個字符串還是常量?這是一個字符串:-) – HamZa 2013-04-23 08:23:20