我正在构建一个带安装的项目(suck as WordPress),用户提供数据库信息(服务器,用户名,密码和数据库)。现在,我必须检查它是否可以连接到提供的数据库。我尝试了这段代码,但似乎它不起作用(我正在使用Mysqli顺便说一句):
public function checkDataBaseConnection($server, $user, $pass, $db)
{
$conn = @mysqli_connect($server, $user, $pass, $db);
if(mysqli_connect_error())
{
return FALSE;
}
else
{
mysqli_close($conn);
return TRUE;
}
}
我还可以使用其他方法来检查服务器是否可以连接到数据库?
答案 0 :(得分:1)
一件事:删除@
,这会抑制一些php警告。
第二件事:试试这个:
public function checkDataBaseConnection($server, $user, $pass, $db)
{
$conn = @mysqli_connect($server, $user, $pass, $db);
if(!$conn)
{
return FALSE;
}
else
{
//mysqli_close($conn); why would you close the connection?
return $conn;
}
}
答案 1 :(得分:0)
你尝试过这样的事吗?
if (checkDataBaseConnection($server, $user, $pass, $db))
echo "Success!";
else
echo "Fail.";
顺便说一句,你可以这样做
mysqli_connect($server, $user, $pass) or die('Connection failed');
答案 2 :(得分:0)
好吧,如果你查看mysqli_connect的PHP页面,你可以看到这个例子:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>