How can PHP submit form data to a database?

To submit form data to a database, you first need to establish a connection to the database. You can use either the MySQLi extension or PDO extension in PHP to connect to and interact with the database.

Here is an example code using the MySQLi extension:

<?php
// 连接到数据库
$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"];

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

// 关闭数据库连接
$conn->close();
?>

Please make sure to properly validate and filter user input in actual use to prevent security issues such as SQL injection.

bannerAds