1

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);
}
?>
8
  • Is $escaped_values are populated? what is that result of that array? Commented Feb 9, 2018 at 15:54
  • 2
    $_POST['$field'] <-- probably not doing what you're expecting. As a side note, I can't for the life of me work out why this code isn't a syntax error... Commented Feb 9, 2018 at 15:56
  • @JonStirling Yeah that would be a pretty weird name for an index... Commented Feb 9, 2018 at 15:56
  • You need ot change $_POST['$field'] to $_POST[$field] without the '. The single quotes make it a literal key. Commented Feb 9, 2018 at 15:59
  • Where is the syntax error in your opinion? I cant see it. @JonStirling Commented Feb 9, 2018 at 16:00

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

To be more precise: use $POST_[$field] instead of $POST_['$field'] - no single quotes!
Thank you, I've been pulling my hair out over this. I cant believe it was so simple as to removing the quotes :D Thank you all for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.