PHP registration system query not inserting into database

I am having trouble inserting the values “firstname”, “lastname”, “email” and “username” into my database. The only value that correctly gets inserted into the database is the hashed password.
I think the problem may have something to do with the for loop, but to me it seems like it should work.

[php]<?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);
// send email
$emailRecipient = $_POST[“email”];
$subject = ‘Welcome!’;
$message_body = 'You have successfully created an account ’ . $_POST[“username”] . ‘! Welcome.’;
mail($emailRecipient, $subject, $message_body);
}
?>[/php]

If you use prepared statements then you don’t have to escape your variables.

Here’s an example using PDO —>
[php]function saveRegistration(array $data, $pdo) {
$password = password_hash($data[‘password’], PASSWORD_DEFAULT);
$query = ‘INSERT INTO users(username, email, password, dateCreated) VALUES ( :username, :email, :password, NOW())’;
$stmt = $pdo->prepare($query);
$result = $stmt->execute([’:username’ => $data[‘username’], ‘:email’ => $data[‘email’], ‘:password’ => $password]);
if ($result) {
return TRUE;
} else {
return FALSE;
}
}[/php]

It isn’t the greatest, but it shows what I’m talking about. Here’s a good link explaining PDO better than I can: https://phpdelusions.net/pdo

This is throwing a warning,

[php]$_POST[’$field’][/php]

Using prepared statements or simply doing something like [php]$email = htmlspecialchars($_POST[‘email’]) [/php]will most likely eliminate that nonsense he’s doing.

Though yes he definitely has a booboo with [php]$_POST[’$field’] [/php] ;D which probably was caused by his editor automatically filling in the quotes.

Sponsor our Newsletter | Privacy Policy | Terms of Service