mfredy mfredy - 1 month ago 6
MySQL Question

Not being able to Insert data into MYSQL tables using PHP

I am trying to insert data into MySQL tables but I am not sure why it is not working

<?php
include 'connect.php';
$userName = $_POST['name'];
$firstname = $_POST['FirstName'];
$Surname = $_Post['Surname'];
$email = $_POST['EmailAddress'];
$password = $_POST['Password'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`)
VALUES ('.$userName.','.$password.','.$firstname.','.$Surname.', '.$gender.', '.$dob.', '.$email.')';
$stmt = $conn->prepare($query);
try {
$myarray = array(
":userName" => $userName,
":password" => $password,
":firstname" =>$firstname,
":Surname" => $Surname,
":gender" => $gender,
":dob" => $dob,
":email" => $email);
print_r($myarray);
$stmt->execute($myarray);
} catch(PDOException $err) {
echo "Houston we have a problem: $err";
}
?>


Please tell me if I am doing something wrong.

Answer

You're using Prepared Statements wrong. With $db->prepare() you're actually submitting the query with placeholders and not with the values (called sending a template). In your case:

$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`) 
                VALUES (:userName, :password, :firstname, :Surname, :gender, :dob, :email)';
Comments