How to create a database through php, this article will introduce in detail the operation of creating a database in php.
Instance (MySQLi - Object-oriented)
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
//Create database
$sql = "CREATE DATABASE myDB";if ($conn->query($sql) === TRUE) { echo "数据库创建成功";} else { echo "Error creating database: " . $conn->error;}$conn->close();?>
Note: When you create a new database , you must specify three parameters (servername, username and password) for the mysqli object.
Tip: If you use another port (default is 3306), add an empty string for the database parameters, such as: new mysqli("localhost", "username", "password", "", port)
Instance (MySQLi Procedural)
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("连接失败: " . mysqli_connect_error()); }
//Create database
$sql = "CREATE DATABASE myDB";if (mysqli_query($conn, $sql)) { echo "数据库创建成功";} else { echo "Error creating database: " . mysqli_error($conn);}mysqli_close($conn);?>
Note: The following uses the PDO instance to create the database "myDBPDO":
Instance
Using PDO:
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // 设置 PDO 错误模式为异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE myDBPDO"; // 使用 exec() ,因为没有结果返回 $conn->exec($sql); echo "数据库创建成功<br>"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
This article introduces in detail how to create a database through php. For more learning materials, please pay attention to the php Chinese website.
Related recommendations:
PHP knowledge related to connecting to MySQL and its operations
PHP MySQL introduction (database related knowledge)
PHP MySQL operations and methods for reading data
The above is the detailed content of How to create a database via PHP MySQL. For more information, please follow other related articles on the PHP Chinese website!