I'm trying to create a form and import submitted data to a database,
<?php
// db has to be manually created first
$host = "localhost";
$userName = "user";
$password = "";
$dbName = "test";
// Create database connection
$conn = new mysqli($host, $userName, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if((isset($_POST['your_name'])&& $_POST['your_name'] !='') && (isset($_POST['your_email'])&& $_POST['your_email'] !=''))
{
$yourName = $conn->real_escape_string($_POST['your_name']);
$yourEmail = $conn->real_escape_string($_POST['your_email']);
$yourPhone = $conn->real_escape_string($_POST['your_phone']);
$comments = $conn->real_escape_string($_POST['comments']);
$sql = "INSERT INTO contact_form_info (name, email, phone, comments)
VALUES (?,?,?,?)";
//$stmt = mysqli_prepare($sql);
//if ($stmt = $conn->prepare(" INSERT INTO contact_form_info WHERE name = ? email = ? phone = ? comments = ? ")) {
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ssss", $yourName, $yourEmail, $yourPhone,$comments);
$stmt->execute();
}
When I submit my form, I get the following error
check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?,?,?)"
Can someone please check my code and tell me what's wrong with it?
And thanks in advance
This error shows that for some reason, the question marks are not being bound to the appropriate variables. MySQL is complaining because the question marks are not encapsulated with ""
.
Ass @RiggsFolly pointed out, you don't need to call $conn->real_escape_string
as you are using prepared statements.
(Also, there is no need to check isset()
and an empty string, empty()
basically does an isset
anyway)
<?php
// db has to be manually created first
$host = "localhost";
$userName = "user";
$password = "";
$dbName = "test";
// Create database connection
$conn = new mysqli($host, $userName, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!empty($_POST['your_name']) && !empty($_POST['your_email']) {
$sql = "INSERT INTO contact_form_info (name, email, phone, comments) VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $_POST['your_name'], $_POST['your_email'], $_POST['your_phone'],$_POST['comments']);
$stmt->execute();
}