2013-03-17 113 views
-1

我想用變量替換mysql連接服務器信息,而不是在我身邊拋出一個錯誤。PDO和變量php

$objDb = new PDO('mysql:host=localhost;dbname=mydb', 'root', ''); 

希望它看起來像這樣:

我都試過,但沒有成功;

$objDb = new PDO('mysql:host=$host;dbname=$db', $user, $pass); 
+0

只要是完全肯定的是,什麼是$主機和$ DB的價值? – 2013-03-17 19:23:27

回答

1

使用雙引號:

$objDb = new PDO("mysql:host=$host;dbname=$db", $user, $pass); 
0

嘗試:

$objDb = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass); 

或者:

$objDb = new PDO("mysql:host=$host;dbname=$db", $user, $pass); 
0

使用此:

// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword); 
// Pre:  $dbHost is the database hostname, 
//   $dbName is the name of the database itself, 
//   $dbUsername is the username to access the database, 
//   $dbPassword is the password for the user of the database. 
// Post: $db is an PDO connection to the database, based on the input parameters. 
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword) 
{ 
    try 
    { 
     return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUsername, $dbPassword); 
    } 
    catch(PDOException $PDOexception) 
    { 
     exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>"); 
    } 
} 

所以,你可以這樣做:

$host = 'localhost'; 
$user = 'root'; 
$databaseName = 'databaseName'; 
$pass = ''; 

$db = connectToDatabase($host, $databaseName, $user, $pass);