php 规范:如何将 HTML 表单数据保存到 MySQL 数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24245012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:14:21  来源:igfitidea点击:

Canonical: How to save HTML form data into MySQL database

phpmysqlforms

提问by vhu

This is a canonical question and answer for saving data from (HTML) form to MySQL database using PHP.

这是使用 PHP 将数据从 (HTML) 表单保存到 MySQL 数据库的规范问答。

This applies to you if you are trying to do the following:

如果您尝试执行以下操作,这适用于您:

  1. Accept user input on a HTML form
  2. Process the input using PHP script
  3. Store the said input into a MySQL database.
  1. 接受用户在 HTML 表单上的输入
  2. 使用 PHP 脚本处理输入
  3. 将所述输入存储到 MySQL 数据库中。

Examples of similar questions asked in the past that should not be used:

过去提出的类似问题不应使用的示例:

Connecting PHP Code and Submit Form to mySQL Database
Insert into mysql using php / html form - not working
How to use PHP to pass HTML form data to a MYSQL db and return the data to the browser
saving form data to database

将 PHP 代码和提交表单连接到 mySQL 数据库
使用 php / html 表单插入 mysql - 不工作
如何使用 PHP 将 HTML 表单数据传递到 MYSQL 数据库并将数据返回到浏览器,
将表单数据保存到数据库

In short, please read on if you questions is: I want to store user input to database using HTML forms, PHP and MySQLor similar.

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

采纳答案by vhu

First of all your PHP or HTML page should produce a form that user can interact with. In the most simple form it'd be something like:

首先,您的 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>

This will give your user a simple form with single input field and 'save' button. After clicking the 'save' button for content will be sent to your 'yourscript.php' using POSTmethod.

这将为您的用户提供一个带有单个输入字段和“保存”按钮的简单表单。单击“保存”按钮后,内容将使用POST方法发送到您的“yourscript.php” 。

yourscript.phpshould implement the following:

yourscript.php应执行以下操作:

  1. Accept and process the input from your form.
  2. Connect to your MySQL database.
  3. Store into the database.
  1. 接受并处理表单中的输入。
  2. 连接到您的 MySQL 数据库。
  3. 存入数据库。

In most simplistic form this would be:

在最简单的形式中,这将是:

<!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://stackoverflow.com/a/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://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php 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://stackoverflow.com/a/2894530
  -->
 <input type="text" name="yourfield" value="<?php print $yourfield; ?>">
 <input type="submit" name="youraction" value="save">
</form>

</body>
</html>

Key takeaway here is to use prepared statements to avoid SQL injections attacks.

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