mysqli_select_db() 期望参数 1 是 mysqli,给定字符串

2022-08-30 21:28:36

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

警告:mysqli_select_db() 要求参数 1 为 mysqli,D:\Hosting\9864230\html\include\connection.php第 11 行给出的字符串

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

数据库选择失败:

<?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());
}
?>

答案 1

你的论点顺序错误。根据文档,连接是第一位的

<?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');
}

?>

答案 2
// 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_XXX不像mysql_XXX,这些参数不再是可选的。mysqli_select_db()mysqli_error()

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

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

必须使用 not ,才能从 中获取错误,因为后者要求您提供有效的连接。mysqli_connect_error()mysqli_error()mysqli_connect()


推荐