温馨提示×

怎样用php mysql类操作数据库表

PHP
小樊
82
2024-09-22 00:15:39
栏目: 云计算

要使用PHP和MySQL类操作数据库表,首先确保已经安装了MySQL服务器和PHP的MySQL扩展(如MySQLi或PDO)。以下是使用MySQLi扩展操作数据库表的示例步骤:

  1. 连接到MySQL数据库服务器:
$servername = "localhost"; // 服务器地址
$username = "your_username"; // 用户名
$password = "your_password"; // 密码
$dbname = "your_database"; // 数据库名

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
  1. 创建数据表:
$sql = "CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(30) NOT NULL,
    email VARCHAR(50) NOT NULL,
    password VARCHAR(255) NOT NULL
)";

if ($conn->query($sql) === TRUE) {
    echo "数据表创建成功";
} else {
    echo "创建数据表错误: " . $conn->error;
}
  1. 插入数据:
$username = "testuser";
$email = "testuser@example.com";
$password = password_hash("testpassword", PASSWORD_DEFAULT);

$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $username, $email, $password);

if ($stmt->execute() === TRUE) {
    echo "新记录插入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$stmt->close();
  1. 查询数据:
$sql = "SELECT id, username, email, password FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // 输出每行数据
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. " - Password: " . $row["password"]. "<br>";
    }
} else {
    echo "0 结果";
}
$result->free();
  1. 更新数据:
$id = 1;
$new_username = "updated_username";
$new_email = "updated_email@example.com";

$sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $new_username, $new_email, $id);

if ($stmt->execute() === TRUE) {
    echo "记录更新成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$stmt->close();
  1. 删除数据:
$id = 1;

$sql = "DELETE FROM users WHERE id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);

if ($stmt->execute() === TRUE) {
    echo "记录删除成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$stmt->close();
  1. 关闭数据库连接:
$conn->close();

请注意,这只是一个简单的示例。在实际项目中,建议使用PHP框架(如Laravel或Symfony)和ORM(对象关系映射)库来操作数据库表,以提高代码的可维护性和安全性。

0