connect.php无法连接

时间:2014-11-11 18:50:34

标签: php mysql connection

我想要一个网站连接到一个带有connect.php的数据库,所以我在其中创建了一个小测试。但它没有显示数据库连接失败,没有mysql错误。这是代码:

<?php
$servername = "localhost";
$username = "sqluser";
$password = "Welkom01!";
$dbname = "users";

$connection = mysqli_connect('$servername', '$username', '$password');
if (!$connection){
    die("Database Connection Failed". mysqli_error());
}
$select_db = mysqli_select_db($dbname);
if (!$select_db){
die("Database Selection Failed" . mysqli_error());
}
echo "succes";
?>
你能帮助我吗?提前谢谢

3 个答案:

答案 0 :(得分:2)

删除变量周围的单引号:

$connection = mysqli_connect($servername, $username, $password');

PHP将单引号的内容视为字符串。只有双引号才能正确评估变量:

<?php
$username = 'foo';
echo '$username'; // outputs: '$username'
echo "$username"; // outputs: 'foo';
echo $username; // outputs : 'foo';

此外,您的mysqli_select_db不正确。它应该是:

$select_db = mysqli_select_db($connection, $dbname);

正如弗雷德在下面指出的那样,mysqli_error要求传递连接:

if (!$select_db){
    die("Database Selection Failed" . mysqli_error($connection));
}

答案 1 :(得分:1)

如果在方法/函数中使用单引号,则解释器不会分配变量值。

解决方案可能是:

$connection = mysqli_connect($servername, $username, $password);

您还需要在选择数据库时传递linkid($ connection)。

$select_db = mysqli_select_db($connection, $dbname);

答案 2 :(得分:1)

试试这个:

<?php
$servername = "localhost";
$username = "sqluser";
$password = "Welkom01!";
$dbname = "users";

$connection = mysqli_connect($servername, $username, $password);
if (!$connection){
    die("Database Connection Failed". mysqli_error($connection));
}
$select_db = mysqli_select_db($connection,$dbname);
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
echo "succes";
?>