[英]PHP - Query to insert data into database
I have been creating a registration system, and my code will not insert the fields: firstname
, lastname
, email
and username
into my database, however it will insert the hashed password into my database.我一直在创建一个注册系统,我的代码不会将字段:
firstname
, lastname
, email
和username
插入到我的数据库中,但是它会将散列密码插入到我的数据库中。 I think the problem might have something to do with the for loop, but to me it seems like it should work.我认为问题可能与 for 循环有关,但在我看来它应该可以工作。
<?php
if (isset($_POST['submit'])){
require_once 'config.php';
$hashed_password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$fields = ['firstname', 'lastname', 'email', 'username'];
$escaped_values = [];
foreach($fields as $field){
$escaped_values[$field] = mysqli_real_escape_string($connect, $_POST['$field']);
}
$sql = "INSERT INTO users (firstname, lastname, email, username, password) VALUES ('{$escaped_values["firstname"]}', '{$escaped_values["lastname"]}', '{$escaped_values["email"]}', '{$escaped_values["username"]}', '$hashed_password')";
mysqli_query($connect, $sql);
}
?>
I believe your error is in this line:我相信你的错误在这一行:
$escaped_values[$field] = mysqli_real_escape_string($connect, $_POST['$field']);
You should use $field
in $_POST[]
the same way you are in $escaped_values[]
, specifically, removing the single quotes.您应该像在
$escaped_values[]
一样在$_POST[]
使用$field
,特别是删除单引号。
Right now that loop is reading $field as a literal string each time it loops through, which most likely doesn't exist, giving you an empty $escaped_values
array现在,该循环每次循环时都将 $field 作为文字字符串读取,这很可能不存在,为您提供一个空的
$escaped_values
数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.