为PHP脚本使用MySQL数据库,你可以按照以下步骤进行操作:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "mydatabase";
// 创建数据库连接
$conn = new mysqli($servername, $username, $password);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 创建数据库
$sql = "CREATE DATABASE $dbname";
if ($conn->query($sql) === TRUE) {
echo "数据库创建成功";
} else {
echo "数据库创建失败: " . $conn->error;
}
// 选择数据库
$conn->select_db($dbname);
// 创建表
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "表创建成功";
} else {
echo "表创建失败: " . $conn->error;
}
// 关闭数据库连接
$conn->close();
?>
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "数据插入成功";
} else {
echo "数据插入失败: " . $conn->error;
}
$sql = "UPDATE users SET email='johndoe@example.com' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "数据更新成功";
} else {
echo "数据更新失败: " . $conn->error;
}
$sql = "DELETE FROM users WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "数据删除成功";
} else {
echo "数据删除失败: " . $conn->error;
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "没有数据";
}
$conn->close();
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云