Mysqli 简明教程
MySQLi - Select Database
一旦连接到 MySQL 服务器,就需要选择一个数据库进行操作。这是因为 MySQL Server 可能有多个数据库可用。
Once you get connected with the MySQL server, it is required to select a database to work with. This is because there might be more than one database available with the MySQL Server.
Selecting MySQL Database from the Command Prompt
从 mysql> 提示符中选择数据库非常简单。你可以使用 SQL 命令 use 来选择数据库。
It is very simple to select a database from the mysql> prompt. You can use the SQL command use to select a database.
Example
这里有一个示例来选择名为 TUTORIALS 的数据库 −
Here is an example to select a database called TUTORIALS −
[root@host]# mysql -u root -p
Enter password:******
mysql> use TUTORIALS;
Database changed
mysql>
现在,你已经选择了 TUTORIALS 数据库,并且所有后续操作都将在 TUTORIALS 数据库上执行。
Now, you have selected the TUTORIALS database and all the subsequent operations will be performed on the TUTORIALS database.
NOTE − 所有的数据库名称、表名、表字段名都区分大小写。因此,在提供任何 SQL 命令时,您必须使用适当的名称。
NOTE − All the database names, table names, table fields name are case sensitive. So you would have to use the proper names while giving any SQL command.
Selecting a MySQL Database Using PHP Script
PHP 使用 mysqli_select_db 函数来选择要执行查询的数据库。此函数接受两个参数,并成功时返回 TRUE,失败时返回 FALSE。
PHP uses mysqli_select_db function to select the database on which queries are to be performed. This function takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
mysqli_select_db ( mysqli $link , string $dbname ) : bool
Sr.No. |
Parameter & Description |
1 |
$link Required - A link identifier returned by mysqli_connect() or mysqli_init(). |
2 |
$dbname Required - Name of the database to be connected. |
Example
尝试以下示例以选择数据库 −
Try the following example to select a database −
将以下示例复制粘贴为 mysql_example.php:
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Selecting MySQL Database</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
echo 'Connected successfully<br />';
$retval = mysqli_select_db( $conn, 'TUTORIALS' );
if(! $retval ) {
die('Could not select database: ' . mysqli_error($conn));
}
echo "Database TUTORIALS selected successfully\n";
mysqli_close($conn);
?>
</body>
</html>