如何使用 PHP 准备好的语句插入 MySQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7747868/
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-26 03:18:55  来源:igfitidea点击:

How to insert into MySQLusing a prepared statement with PHP

phpmysqlmysqliprepared-statement

提问by bammab

I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?

我只是在学习数据库,我希望能够存储用户输入。关于如何使用 PHP 获取表单数据并将其保存到数据库的基本示例是什么?

Also making the form secure from SQL attacks.

还使表单免受SQL 攻击

采纳答案by Herbert

File sample.html

文件sample.html

<form action="sample.php" method="POST">
    <input name="sample" type="text">
    <input name="submit" type="submit" value="Submit">
</form>

File sample.php

文件sample.php

<?php
    if (isset($_POST['submit'])) {

        $mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');

        /* Check connection */
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }

        $stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");
        $stmt->bind_param('s', $sample);   // Bind $sample to the parameter

        $sample = isset($_POST['sample'])
                  ? $_POST['sample']
                  : '';

        /* Execute prepared statement */
        $stmt->execute();

        printf("%d Row inserted.\n", $stmt->affected_rows);

        /* Close statement and connection */
        $stmt->close();

        /* Close connection */
        $mysqli->close();
    }
?>

This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is mucheasier, IMHO.

这是一个非常基本的例子。今天,许多 PHP 开发人员正在转向PDO。Mysqli 并没有过时,但恕我直言,PDO容易。