我想用变量替换 mysql 连接服务器信息,而不是在我这边引发错误。
$objDb = new PDO('mysql:host=localhost;dbname=mydb', 'root', '');
希望它看起来像这样:
我试过这个但没有成功;
$objDb = new PDO('mysql:host=$host;dbname=$db', $user, $pass);
使用双引号:
$objDb = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
尝试:
$objDb = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass);
或者:
$objDb = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
用这个:
// 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);