91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

怎樣用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
萨迦县| 宽城| 曲水县| 宜阳县| 孟连| 诸暨市| 桑日县| 浮梁县| 洱源县| 镇沅| 怀远县| 茂名市| 乌苏市| 苍梧县| 宜宾市| 分宜县| 夏邑县| 六安市| 平山县| 屏山县| 灵武市| 巩义市| 临猗县| 佛坪县| 南澳县| 女性| 织金县| 铜陵市| 武义县| 西畴县| 稷山县| 禹州市| 堆龙德庆县| 辛集市| 徐汇区| 永顺县| 宣威市| 海南省| 保山市| 沾化县| 桐城市|