如何使用 PHP 准备好的语句插入 MySQL [英] How to insert into MySQL using a prepared statement with PHP

查看:50
本文介绍了如何使用 PHP 准备好的语句插入 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

还使表单免受SQL 攻击.

推荐答案

File 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 容易得多,恕我直言.

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

这篇关于如何使用 PHP 准备好的语句插入 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆