溫馨提示×

field php怎樣進(jìn)行字段插入

PHP
小樊
81
2024-10-17 10:29:48
欄目: 編程語言

在PHP中,使用MySQLi或PDO擴(kuò)展進(jìn)行數(shù)據(jù)庫操作。以下是使用MySQLi和PDO分別插入數(shù)據(jù)到數(shù)據(jù)庫表中的示例。

1. 使用MySQLi:

首先,確保已安裝MySQL數(shù)據(jù)庫并創(chuàng)建一個(gè)包含所需字段的表。然后,使用以下代碼插入數(shù)據(jù):

<?php
// 數(shù)據(jù)庫連接信息
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 創(chuàng)建連接
$conn = new mysqli($servername, $username, $password, $dbname);

// 檢查連接
if ($conn->connect_error) {
    die("連接失敗: " . $conn->connect_error);
}

// 要插入的數(shù)據(jù)
$name = "John Doe";
$email = "john.doe@example.com";
$age = 30;

// 插入數(shù)據(jù)的SQL語句
$sql = "INSERT INTO your_table (name, email, age) VALUES ('$name', '$email', $age)";

// 執(zhí)行SQL語句并檢查是否成功
if ($conn->query($sql) === TRUE) {
    echo "新記錄插入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

// 關(guān)閉連接
$conn->close();
?>

2. 使用PDO:

同樣,確保已安裝MySQL數(shù)據(jù)庫并創(chuàng)建一個(gè)包含所需字段的表。然后,使用以下代碼插入數(shù)據(jù):

<?php
// 數(shù)據(jù)庫連接信息
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

try {
    // 創(chuàng)建連接
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // 設(shè)置 PDO 錯誤模式為異常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 要插入的數(shù)據(jù)
    $name = "John Doe";
    $email = "john.doe@example.com";
    $age = 30;

    // 插入數(shù)據(jù)的SQL語句
    $sql = "INSERT INTO your_table (name, email, age) VALUES (:name, :email, :age)";

    // 使用預(yù)處理語句執(zhí)行SQL語句
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':age', $age);

    // 執(zhí)行SQL語句并檢查是否成功
    if ($stmt->execute()) {
        echo "新記錄插入成功";
    } else {
        echo "Error: " . $sql . "<br>" . $stmt->error;
    }
} catch(PDOException $e) {
    echo "連接失敗: " . $e->getMessage();
}

// 關(guān)閉連接
$conn = null;
?>

請注意,這兩個(gè)示例中的your_tableyour_username、your_passwordyour_database需要替換為您自己的數(shù)據(jù)庫表和登錄憑據(jù)。同時(shí),根據(jù)實(shí)際情況調(diào)整字段名稱和數(shù)據(jù)。

0