How to fix this SQL syntax error? - php

How do I fix this error?
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1."
I'm using wamp server. localhost:81.
<?php
$conn =mysqli_connect('localhost', 'root' , '','register');
if(isset($_POST['submit']))
{
$fname=$_POST['FName'];
$mname = $_POST['UName'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$gender = $_POST['gender'];
$Password = $_POST['Pass'];
$Repassword = $_POST['Rpass'];
$sql = "INSERT INTO registered(FullName,UserName,Email,Contact#,Gender,Password,RPassword) values('$fname','$mname','$email','$contact','$gender','$Password','$Repassword')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
print '<script>alert("Successfully Submit Data!");</script>';
}
else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>

I would recommend using backticks (`) around your column names, to prevent SQL from seeing it as something else. You also want to make sure you escape the data as well.
$sql = "INSERT INTO `registered`
(`FullName`, `UserName`, `Email`, `Contact#`, `Gender`, `Password`, `RPassword`)
VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sssssss', $fname, $mname, $email, $contact, $gender, $Password, $Repassword);
if ( $stmt->exec() ) {
//Success
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
For more information on SQL Injection, and how it can effect you, please check out this post.

try this
INSERT INTO `registered`(`FullName`,`UserName`,`Email`,`Contact#`,`Gender`,`Password`,`RPassword`)
values('$fname','$mname','$email','$contact','$gender','$Password','$Repassword')";

try this
$sql = "INSERT INTO registered(FullName,UserName,Email,Contact#,Gender,Password,RPassword)
values($fname,$mname,$email,$contact,$gender,$Password,$Repassword)";

Related

prepared statement sets column to null

I'm trying to set my code from escape strings to prepared statements. I'm getting an error message, that says Column 'name' cannot be null. The 'name' column should be coming from a post method. I'm not sure if using question marks is a good way, but that's what they write on different pages.
<form action="inserttest.php" method="post">
my insert code:
<?php
session_start();
$link = mysqli_connect("localhost", "root", "", "reg");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Prepare an insert statement
$sql = "INSERT INTO cards (name, phone, phone2, email, zipcode, address, job, description, userid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssssisssi", $name, $phone, $phone2, $email, $zipcode, $address, $job, $description, $userid);
if(isset($_POST['name'])){
$name = $_POST['name'];
}
if(isset($_POST['phone'])){
$phone = $_POST['phone'];
}
if(isset($_POST['phone2'])){
$phone2 = $_POST['phone2'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['zipcode'])){
$zipcode = $_POST['zipcode'];
}
if(isset($_POST['address'])){
$address = $_POST['address'];
}
if(isset($_POST['job'])){
$job = $_POST['job'];
}
if(isset($_POST['description'])){
$description = $_POST['description'];
}
if(isset($_SESSION['id'])){
$userid = $_SESSION['id'];
}
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
If your are going to check if POST parameter are set i.e. if(isset($_ ... then provide an else statement.
if(isset($_POST['name'])){
$name = $_POST['name'];
} else {
$name = 'No name was provided';
}
If the name is important and must be provided: You can put it at the top of your query before you execute it, and exit the result if it is not provided
if(isset($_POST['name'])){
$name = $_POST['name'];
} else {
die('Name has to be provided to proceed');
}
Other checks: Check if your form has the name field and it is named correctly.

MySQL Error - MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?)'

I am a CS freshman and I am currently learning PHP/MySQL on my own. I was able to send a contact form to the mySQL db via PHP. Now I am using mysqli prepared statements to protect my code against mySQL injections but I am having trouble. I created a new file called contact_check.php.
The error I am getting is:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?)' at line 2. Do you know what is the error?
contactform.php
<?php
require("../config/db.php");
require("contact_check.php");
$link = mysqli_connect("localhost","root","","benoit");
if(isset($_POST["submit"])){
$name = $_POST["name"];
$company = $_POST["company"];
$emailFrom = $_POST["email"];
$phone = $_POST["phone"];
$message = htmlspecialchars($_POST["message"]);
$mailTo = "pamousset01#gmail.com";
$headers = "From:".$emailFrom;
$txt = "You have received an email from ".$name.".\n\n\n".$message;
mysqli_query($link,"INSERT INTO contact (`name`, `email`, `company`, `phone`, `message`)
VALUES (?, ?, ?, ?, ?)") or die(mysqli_error($link));
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL error";
} else{
mysqli_stmt_bind_param($stmt, "sssss", $name, $company, $emailFrom, $phone, $message);
mysqli_stmt_execute($stmt);
}
mail($mailTo, $name, $txt, $headers);
header("Location: contact.php?mailsend");
}
?>
contact_check.php
<?php
$data = "Admin";
//Template
$sql = "SELECT * FROM contact where name=?;";
//Prepared statement
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt, $sql)){
echo "error";
} else{
mysqli_stmt_bind_param($stmt, "s", $data);
//run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while($row = mysqli_fetch_assoc($result)){
echo $row["user_uid"] . "<br>";
}
}
?>
db.php
<?php
$dbServerName = "localhost";
$dbUserName = "root";
$dbPassword = "";
$dbName = "benoit";
$conn = mysqli_connect($dbServerName, $dbUserName, $dbPassword, $dbName);
if(mysqli_connect_error()){
echo"failed to connect to MYSQL" . mysqli_connect_error();
}
?>
BTW you are not escaping your user input which could lead to syntax errors and SQL injections. Use Prepared Statements.
Also check your column name as sad above it might be that you referenced one wrong.

PHP Insert Prepared Statement

I looking through different post regarding prepared statements. I am getting the following error
ERROR: Could not prepare query: INSERT INTO contact (, ,) VALUES (?,
?). You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ' , , , ) VALUES (?, ?)' at line 1
I can't seem to figure out why I am getting this error. Everything I find online hasn't been helpful. I am hoping someone can point me in the right direction.
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Prepare an insert statement
$sql = "INSERT INTO tablename (name, email) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
// Set parameters
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
Thank you,
Found the answer for this issue.
<?php
$servername = "mysql";
$username = "root";
$password = "passwrd";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO tablename (name, email, commtype,
comment, confirm)
VALUES (:name, :email, :commtype, :comment, :confirm)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':commtype', $commtype);
$stmt->bindParam(':comment', $comment);
$stmt->bindParam(':confirm', $confirm);
// insert a row
$name = $_POST['name'];
$email = $_POST['email'];
$commtype = $_POST['commtype'];
$comment = $_POST['comment'];
$confirm = $_POST['confirm'];
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

Why does the following not appear to open an SQL connection?

I find that the folowing script hangs for some reason. It will load and PHP doesn't see any errors, but it will not process the data (noting that we are in a context where I have a seperate login database open.)
In process.php we have the following:
<? PHP
//Process the POST data in prepration to write to SQL database.
$_POST['chat_input'] = $input;
$time = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_SESSION['username'];
$servername = "localhost";
$username = "id3263427_chat_user";
$password = "Itudmenif1!Itudmenif1!";
$dbname = "id3263427_chat_user";
$id = "NULL";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`,
`message`) VALUES ('$id','$name', '$ip', '$time', '$input')';
if(mysqli_query($link, $sql)){
mysqli_close($conn);
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
the html form passed to the script above is as follows:
<form action="/process.php" method="post" id="chat">
<b> Send A Message (500 Character Max):</b><br>
<textarea name="chat_input" form="chat" size="500"></textarea>
<input type="submit" value=submit>
</form>
Not sure what's going on with this.
You got the syntax error because you're closing the $sql string before $id with your '.
What is this about your $id variable? With your current code you will insert the String "NULL". If you want to set the sql value null you should use $id = null; or just don't insert any value.
If you want your database to set an id, also leave it blank.
$input = $_POST['chat_input'];
$id = null;
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
First solution
If this isn't a production code, you could insert the variables directly into the statement, but you should use " instead of ' for your sql string, so you can insert variables and ' without closing the string.
$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')";
if($conn->query($sql) === true) {
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " .$conn->error;
$conn->close();
}
Second solution
A better approach would be a prepared statement.
$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)');
$stmt->bind_param("ssss", $username, $ip, $time, $input);
if($stmt->execute()) {
$stmt->close();
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $stmt. " . $conn->error;
$stmt->close();
$conn->close();
}
The "s" in bind_param() defines a string at the given position, if you want to insert an integer, use "i" instead.
e.g. bindParam("sis", $string, $integer, $string);

MySQL error because of syntax in Custom PHP code

I am trying to enter user's data into a database. I think the commas in the address are causing the error.
<?php
$full_name = $_POST["fullname"];
$email = $_POST["email"];
$password = $_POST["password"];
$full_address = $_POST["address"];
$city = $_POST["city"];
$age = $_POST["age"];
$contact_number = $_POST["number"];
$gender = $_POST["gender"];
$education = $_POST["education"];
?>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
As others have noted, your code is vulnerable to SQL injections. You should consider using parameterized queries:
$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
For more information refer to the PHP manual on MySQLi prepared statements.
You need to quote string in your SQL statement;
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ('$full_name', '$email', '$password','$full_address','$city',$age,'$contact_number','$gender','$education')";
Notice the single quotes around all the variables that contain strings. I might be a bit off because I don't know the values or table structure.
But the just quote all values that are going in to a Date or Text field.
To avoid additional problems and security risks you should be using mysqli_real_escape_string (at a minimum).
In all your assignment statements wrap the values in mysqli_real_escape_string
$full_name = mysqli_real_escape_string($conn, $_POST["fullname"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
...
Note this requires setting up your DB connection before the variable assignments, so you'll have to reorganize your code a bit.
rink.attendant.6's answer is the proper way to adapt your code.

Categories