Connecting to the root user in PHP can be achieved by using the mysqli or PDO extensions.
Use the mysqli extension:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检查连接是否成功
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 创建数据库
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "数据库创建成功";
} else {
echo "创建数据库时出错: " . mysqli_error($conn);
}
// 关闭连接
mysqli_close($conn);
?>Use the PDO extension:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "连接成功";
// 创建数据库
$sql = "CREATE DATABASE myDB";
// 使用 exec() 方法执行 SQL 语句
$conn->exec($sql);
echo "数据库创建成功";
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 关闭连接
$conn = null;
?>In the above example, suppose you want to create a database named "myDB". When connecting as the root user, you can omit the database name and then use the "CREATE DATABASE" command in an SQL statement to create the database.