PHP:将表单中的值插入到MySQL中 [英] PHP: Inserting Values from the Form into MySQL

查看:91
本文介绍了PHP:将表单中的值插入到MySQL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在终端中创建了一个 users mysql ,我尝试创建一个简单的任务:insert values从形式。这是我的 dbConfig文件

 <?php 
$ mysqli = new mysqli(localhost,root,pass,testDB);如果(mysqli_connect_errno()){
printf(连接失败:%s\\\
,mysqli_connect_error());
$ b $ / *检查连接* /

exit();
}
?>

这是我的 Index.php

 <!doctype html> 
< html>
< head>
< meta charset =utf-8>
< meta http-equiv =X-UA-Compatiblecontent =IE = edge,chrome = 1>
< meta name =descriptioncontent =$ 1>
< meta name =viewportcontent =width = device-width,initial-scale = 1>

< link rel =stylesheettype =text / csshref =style.css>

< title> test< / title>

<?php
include_once'dbConfig.php';
?>

< / head>
< body>
<?php
if(isset($ _ POST ['save'])){
$ sql =INSERT INTO users(username,password,email)
VALUES '[用户名 ]。$ _ POST', ' [密码 $ _ POST',' [电子邮件 $ _ POST。');
}

?>

< form method =post>
< label id =first>名字:< / label>< br />
< input type =textname =username>< br />

< label id =first>密码< / label>< br />
< input type =passwordname =password>< br />

< label id =first>电子邮件< / label>< br />
< input type =textname =email>< br />

< button type =submitname =save> save< / button>
< button type =submitname =get> get< / button>
< / form>

< / body>
< / html>

点击我的保存按钮后,没有任何反应,数据库仍然是空的。我尝试了 echo'ing INSERT 查询,并且它从表单中获取所有值。在我试图检查这是否从终端工作后,我登录到我的 sql 尝试返回用户表中的所有数据,并获得空集。

解决方案

以下代码只是声明一个包含MySQL查询的字符串变量:

$ sql =INSERT INTO users(username,password,email)
VALUES('。$ _ POST [username]。'','。$ _ POST [password]。'' ,''。$ _ POST [email]。');



它不执行查询。为了做到这一点,你需要使用一些功能,但首先让我解释一些其他的东西。

不要输入用户信息:你不应该追加用户输入(例如 $ _GET 或 $ _ POST 直接的表单输入查询。有人可以以这种方式仔细操纵输入,以便对数据库造成严重损害。这就是所谓的SQL注入。您可以阅读更多有关此处



为保护您的脚本免受此类攻击,您必须使用准备好的语句。更多关于准备好的声明此处



将准备好的语句包含到您的代码中,如下所示:

$ sql =INSERT INTO users(username,password,email)
VALUES(?,?,?)



注意用作值的占位符。接下来,您应该使用 mysqli_prepare 准备语句:
$ b

$ stmt = mysqli_prepare($ sql );然后开始将输入变量绑定到准备好的语句:

$ stmt-> bind_param(sss,$ _POST ['username'],$ _POST ['email'],$ _POST ['password']);



最后执行准备好的语句。 (这是实际插入发生的地方)

$ stmt-> execute();



注意尽管不是问题的一部分,但我强烈建议您不要以明文形式存储密码。相反,您应该使用 password_hash 来存储密码的散列


I created a users table in mysql from the terminal and I am trying to create simple task: insert values from the form. This is my dbConfig file

<?php
$mysqli = new mysqli("localhost", "root", "pass", "testDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
?>

and This is my Index.php .

<!doctype html>
<html>
 <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="$1">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="style.css">

    <title>test</title>

    <?php
    include_once 'dbConfig.php';
    ?>

</head>
<body>
     <?php
    if(isset($_POST['save'])){
        $sql = "INSERT INTO users (username, password, email)
        VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";
    }

    ?>

    <form method="post"> 
    <label id="first"> First name:</label><br/>
    <input type="text" name="username"><br/>

    <label id="first">Password</label><br/>
    <input type="password" name="password"><br/>

    <label id="first">Email</label><br/>
    <input type="text" name="email"><br/>

    <button type="submit" name="save">save</button>
    <button type="submit" name="get">get</button>
    </form>

</body>
</html>

After hitting my save button, nothing happens, database is still empty. I tried echo'ing the INSERT query and it takes all values from the form as it is supposed to. After I try to check if this worked from terminal, I login into my sql try to return all data from users table and I get empty set.

解决方案

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email) VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email) VALUES (?,?,?)"

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

这篇关于PHP:将表单中的值插入到MySQL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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