溫馨提示×

php怎么提交表單數(shù)據(jù)到數(shù)據(jù)庫

小億
104
2024-01-19 09:49:57
欄目: 編程語言

要將表單數(shù)據(jù)提交到數(shù)據(jù)庫,首先需要連接到數(shù)據(jù)庫??梢允褂肞HP的MySQLi擴(kuò)展或PDO擴(kuò)展來連接和操作數(shù)據(jù)庫。

以下是一個(gè)使用MySQLi擴(kuò)展的示例代碼:

<?php
// 連接到數(shù)據(jù)庫
$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);
}

// 處理表單提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    // 插入數(shù)據(jù)到數(shù)據(jù)庫
    $sql = "INSERT INTO your_table (name, email, message) VALUES ('$name', '$email', '$message')";
    if ($conn->query($sql) === TRUE) {
        echo "數(shù)據(jù)提交成功";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// 關(guān)閉數(shù)據(jù)庫連接
$conn->close();
?>

請注意,在實(shí)際使用中,應(yīng)該對用戶輸入進(jìn)行適當(dāng)?shù)尿?yàn)證和過濾,以防止SQL注入等安全問題。

0