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

如何在PHP中使用准备好的语句插入MySQL,php,mysql,mysqli,prepared-statement,Php,Mysql,Mysqli,Prepared Statement,我只是在学习数据库,我希望能够存储用户输入。关于如何使用PHP获取表单数据并将其保存到数据库的基本示例是什么 还可以通过。File sample.html使表单安全 文件sample.php 这是一个非常基本的例子。今天,许多PHP开发人员正在转向。Mysqli并没有过时,但PDO要容易得多,IMHO。查看PDO:+1表示希望学会正确操作。:)php手册中的real\u escape\u string()也是多余的。使用预处理语句的全部目的是避免必须手动转义这些值。 <form a

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

还可以通过。

File sample.html使表单安全

文件sample.php

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

查看PDO:+1表示希望学会正确操作。:)php手册中的
real\u escape\u string()
也是多余的。使用预处理语句的全部目的是避免必须手动转义这些值。
<form action="sample.php" method="POST">
    <input name="sample" type="text">
    <input name="submit" type="submit" value="Submit">
</form>
<?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();
    }
?>