【问题标题】:How to insert into MySQL using a prepared statement with PHP [duplicate]如何使用 PHP 准备好的语句插入 MySQL [重复]
【发布时间】:2011-12-06 13:35:35
【问题描述】:

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

还使表单安全来自SQL attacks

【问题讨论】:

标签: php mysql mysqli prepared-statement


【解决方案1】:

文件 sample.html

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

文件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();
    }
?>

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

【讨论】:

  • real_escape_string() 是多余的。使用准备好的语句的全部意义在于避免手动转义值。
猜你喜欢
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多