简体   繁体   中英

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. I think the problem might have something to do with the for loop, but to me it seems like it should work.

<?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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM