淘先锋技术网

首页 1 2 3 4 5 6 7

MySQL是一种关系型数据库管理系统,经常被用于构建Web应用程序。它是一个开源的,具有高可靠性和性能的可定制性数据库解决方案。

// 连接数据库
$serverName = "localhost";
$userName = "root";
$password = "123456";
$databaseName = "mydb";
$conn = mysqli_connect($serverName, $userName, $password, $databaseName);
// 创建表格
$sql = "CREATE TABLE customers (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table customers created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
// 插入数据
$sql = "INSERT INTO customers (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn); } // 查询数据 $sql = "SELECT * FROM customers"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) >0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. " - Email: " . $row["email"]. "
"; } } else { echo "0 results"; } // 关闭连接 mysqli_close($conn);

以上代码展示了如何连接MySQL数据库,创建表格,插入和查询数据,以及关闭连接。使用MySQL可以轻松地管理和存储数据,是开发Web应用程序的必要工具之一。