亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

怎樣用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
古交市| 得荣县| 龙南县| 武宁县| 宜春市| 驻马店市| 独山县| 汉寿县| 常宁市| 南漳县| 乌兰察布市| 革吉县| 仙桃市| 读书| 京山县| 察隅县| 枣强县| 湖北省| 华坪县| 登封市| 阿勒泰市| 余干县| 江孜县| 望都县| 阳曲县| 黑龙江省| 洛川县| 石嘴山市| 彰武县| 霍林郭勒市| 仁怀市| 道孚县| 什邡市| 汝南县| 亳州市| 杭锦后旗| 泽州县| 新乡市| 邳州市| 巴林左旗| 马龙县|