数据库名怎么查php
时间 : 2023-03-28 01:53:01声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

在 PHP 中,要查看当前使用的数据库名,可以使用 MySQLi 扩展中的 mysqli_select_db 函数。该函数的语法如下:

```php

mysqli_select_db($connection, $dbname);

其中,$connection 为连接数据库的对象(即 mysqli_connect 函数返回的对象),$dbname 为要选择的数据库名。

以下是一个示例代码:

```php

// 连接数据库

$connection = mysqli_connect("localhost", "root", "password");

// 检查是否连接成功

if (!$connection) {

die("连接失败:" . mysqli_connect_error());

}

// 选择数据库

$dbname = "mydatabase";

mysqli_select_db($connection, $dbname);

// 输出当前数据库名

echo "当前使用的数据库名为:" . mysqli_info($connection);

以上代码通过 mysqli_select_db 函数选择名为 mydatabase 的数据库,并通过 mysqli_info 函数输出当前使用的数据库名。

需要注意的是,如果选择的数据库不存在,mysqli_select_db 函数将返回 false。因此,在使用该函数时应该进行异常处理,以避免程序崩溃。

要查看PHP中的数据库名,可以使用MySQLi或PDO扩展中的功能来连接和查询数据库。

使用MySQLi扩展

使用MySQLi扩展中的功能可以连接到MySQL数据库并执行查询。

以下是一个示例代码,用于连接到MySQL数据库并查询数据库名称:

<?php

// Database variables

$host = "localhost";

$username = "root";

$password = "password";

// Create a MySQLi object and connect to the database

$mysqli = new mysqli($host, $username, $password);

// Check for connection errors

if ($mysqli->connect_errno) {

echo "Failed to connect to MySQL: " . $mysqli->connect_error;

exit();

}

// Run the query to get the database name

$sql = "SELECT DATABASE()";

// Execute the query

$result = $mysqli->query($sql);

// Fetch the result

$row = $result->fetch_array();

// Output the database name

echo "Connected to database: " . $row[0];

// Close the connection

$mysqli->close();

?>

使用PDO扩展

使用PDO扩展中的功能可以连接到各种类型的数据库以及执行查询。

以下是一个示例代码,用于连接到MySQL数据库并查询数据库名称:

<?php

// Database variables

$host = "localhost";

$username = "root";

$password = "password";

$database = "my_database";

// Create a PDO object and connect to the database

$dsn = "mysql:host=$host;dbname=$database";

$pdo = new PDO($dsn, $username, $password);

// Run the query to get the database name

$sql = "SELECT DATABASE()";

// Prepare the query

$stmt = $pdo->prepare($sql);

// Execute the query

$stmt->execute();

// Fetch the result

$row = $stmt->fetch();

// Output the database name

echo "Connected to database: " . $row[0];

// Close the connection

$pdo = null;

?>

总之,无论使用哪种扩展,都可以连接到MySQL数据库并查询数据库名称。