17

我是 Mysqli_* 的新手,我收到以下错误:

警告:mysqli_select_db() 期望参数 1 为 mysqli,字符串在第 11 行的 D:\Hosting\9864230\html\includes\connection.php 中给出

警告:mysqli_error() 需要 1 个参数,0 在第 13 行的 D:\Hosting\9864230\html\includes\connection.php 中给出

数据库选择失败:

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
    die("Database connection failed: " . mysqli_error());
}

// 2. Select a database to use 
$db_select = mysqli_select_db(DB_NAME,$connection);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error());
}
?>
4

2 回答 2

58

你的论点顺序错误。根据文档,连接首先出现

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>
于 2012-12-20T19:35:42.980 回答
6
// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

你得到了倒数的参数mysqli_select_db()顺序。并mysqli_error()要求您提供连接参数。mysqli_XXX 不像 mysql_XXX,这些参数不再是可选的。

另请注意,使用 mysqli 您可以在以下位置指定数据库mysqli_connect()

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

必须使用mysqli_connect_error(), notmysqli_error()来获取错误mysqli_connect(),因为后者要求您提供有效的连接。

于 2012-12-20T19:35:29.453 回答