规范化(Canonical):如何将HTML表单数据保存到MySQL数据库中

7
这是一个关于使用PHP将(HTML)表单数据保存到MySQL数据库的问题和答案。
如果您正在尝试执行以下操作,则适用于您:
1. 在HTML表单上接受用户输入 2. 使用PHP脚本处理输入 3. 将所述输入存储到MySQL数据库中。
过去类似问题的示例不应使用: 连接PHP代码和提交表单到我的SQL数据库 使用php / html表单插入mysql - 不起作用 如何使用PHP将HTML表单数据传递到MYSQL数据库并将数据返回给浏览器 将表单数据保存到数据库

简而言之,如果您的问题是:“我想使用HTML表单、PHP和MySQL将用户输入存储到数据库中”,或类似问题,请继续阅读。


请添加更多关于如何使用复选框和其他表单元素的示例。这样可以避免未来重复提问,并在需要时更新此问题的其他变体。 - vhu
2
大多数链接中都包含了已弃用的 mysql_* 函数。你应该至少找到一些使用 mysqli_* 函数的链接。此外,最好使用预处理语句的链接。例如mysqli_* with prepared statements,或者使用prepared statementsPDO - Funk Forty Niner
@Fred-ii-:这就是它们链接的部分原因。SQL注入在答案中有所涉及。我想我在问题部分需要更具体一些。 - vhu
这是我有时回答那些认为使用PDO是安全的人的话:“使用mysqli_和/或PDO并不能单独防止SQL注入。使用准备好的语句mysqli_*,或者使用准备好的语句与PDO会更加安全。” - Funk Forty Niner
1个回答

6

首先,您的PHP或HTML页面应该生成一个用户可以与之交互的表单。最简单的形式可能是:

<html>
<body>
 <form method="post" action="yourscript.php">
  <input type="text" name="yourfield">
  <input type="submit" name="youraction" value="save">
 </form>
</body>
</html>

这将为您的用户提供一个简单的表单,其中包含单个输入字段和“保存”按钮。单击“保存”按钮后,内容将使用POST方法发送到您的“yourscript.php”。 yourscript.php应实现以下功能:
  1. 接受并处理来自表格的输入。
  2. 连接到您的MySQL数据库。
  3. 将数据存储到数据库中。
在最简单的形式中,这将是:
<!doctype html>
<html>
 <head>
  <title>Process and store</title>
 </head>
<body>
<?php

// Check that user sent some data to begin with. 
if (isset($_REQUEST['yourfield'])) {

    /* Sanitize input. Trust *nothing* sent by the client.
     * When possible use whitelisting, only allow characters that you know
     * are needed. If username must contain only alphanumeric characters,
     * without puntation, then you should not accept anything else.
     * For more details, see: https://stackoverflow.com/a/10094315
     */
    $yourfield=preg_replace('/[^a-zA-Z0-9\ ]/','',$_REQUEST['yourfield']);

    /* Escape your input: use htmlspecialchars to avoid most obvious XSS attacks.
     * Note: Your application may still be vulnerable to XSS if you use $yourfield
     *       in an attribute without proper quoting.
     * For more details, see: https://dev59.com/8HVC5IYBdhLWcg3w-WSs#130323
     */
    $yourfield=htmlspecialchars($yourfield);


} else {
    die('User did not send any data to be saved!');
}


// Define MySQL connection and credentials
$pdo_dsn='mysql:dbname=yourdatabase;host=databasehost.example.com';
$pdo_user='yourdatabaseuser';     
$pdo_password='yourdatabaspassword';  

try {
    // Establish connection to database
    $conn = new PDO($pdo_dsn, $pdo_user, $pdo_password);

    // Throw exceptions in case of error.
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Use prepared statements to mitigate SQL injection attacks.
    // See https://dev59.com/oHVD5IYBdhLWcg3wL4cA for more details
    $qry=$conn->prepare('INSERT INTO yourtable (yourcolumn) VALUES (:yourvalue)');

    // Execute the prepared statement using user supplied data.
    $qry->execute(Array(":yourvalue" => $yourfield));

} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage() . " file: " . $e->getFile() . " line: " . $e->getLine();
    exit;
}
?>
<form method="post">

 <!-- Please note that the quotes around next <?php ... ?> block are important
      to avoid XSS issues with poorly escaped user input. For more details:
      https://dev59.com/e3E85IYBdhLWcg3wMQlm#2894530
  -->
 <input type="text" name="yourfield" value="<?php print $yourfield; ?>">
 <input type="submit" name="youraction" value="save">
</form>

</body>
</html>

这里的关键是要使用准备好的语句来避免SQL注入攻击


这个 ('INSERT INTO yourtable VALUES (:yourvalue)') 需要改成 ('INSERT INTO yourtable (your_column) VALUES (:yourvalue)')。最好指定要插入的实际列。 - Funk Forty Niner
处理部分在哪里?我本来期望参考答案会包含一些有关字符集验证、text/*约束或者至少提到HTMLPurifier的详细说明。 - mario

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接