如何使用带有PHP的Prepared Statement插入到mysql中

bam*_*mab 31 php mysql mysqli prepared-statement

所以我只是在学习数据库,我希望能够存储用户输入.有人能给我一个基本的例子来说明如何使用php获取表单数据并将其保存到数据库中吗?还使表单免受sql攻击

Her*_*ert 28

sample.html

<form action="sample.php" method="POST">
    <input name="sample" type="text">
    <input name="submit" type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)

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();
    }
?>
Run Code Online (Sandbox Code Playgroud)

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

  • `real_escape_string()`是多余的.使用预准备语句的重点是避免必须手动转义值. (7认同)