mfredy mfredy - 10 months ago 46
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

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);
} catch(PDOException $err) {
echo "Houston we have a problem: $err";

Please tell me if I am doing something wrong.

Answer Source

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)';