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

查看:79
本文介绍了如何使用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攻击的保护.

Also making the form secure from SQL attacks.

推荐答案

文件 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天全站免登陆