I am getting a Syntax Error in SQL - php

Having trouble submitting data to a database because of syntax error.
Database Structure
database: red_fungi
username: fungi_47
password: *******
Table Structure:
columns > type
id > int(11)
first_name > text
last_name > text
email > text
phone > text
website > text
description > text
As well as the php code:
<?php
$servername = "localhost";
$username = "fungi_47";
$password = "********";
$dbname = "red_fungi";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['first_name']);
$last_name = mysqli_real_escape_string($link, $_POST['last_name']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$phone = mysqli_real_escape_string($link, $_POST['phone']);
$website = mysqli_real_escape_string($link, $_POST['website']);
$comment = mysqli_real_escape_string($link, $_POST['comment']);
$hosting = mysqli_real_escape_string($link, $_POST['hosting']);
$sql = "INSERT INTO contact (id, first_name, last_name, email, phone, website, description, hosting)
VALUES (NULL, $first_name, $last_name, $email, $phone, $website, $comment, $hosting)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When submitting, I see that the post has been successful:
first_name=Bill&last_name=Nye&email=bill%40nye.com&phone=8888888888&website=billnyefungi.com&comment=help%20me%20make%20a%20fungi%20website&hosting=yes
but the post response shows the following error:
Error: INSERT INTO contact (id, first_name, last_name, email, phone, website, description, hosting)
VALUES (NULL, , , , , , , )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 2
However I've checked the syntax and can't see anything wrong with it. Any ideas what's going wrong?

Your sql statement needs to look more like this:
$sql = "INSERT INTO `contact` (`id`, `first_name`, `last_name`, `email`, `phone`, `website`, `description`, `hosting`)
VALUES (NULL, '{$first_name}', '{$last_name}', '{$email}', '{$phone}', '{$website}', '{$comment}', '{$hosting}')";
The first thing I do when I have a problem like this is echo out the sql and see if there are obvious problems
and follow up on all the data validation & security points made by other users.

Your code is assuming that $_POST['XXX'] will be populated, and it isn't. Thats what all those ,,,,,,,, mean in the error.
Instead, first check if $_POST['XXX'] is created, and has a value prior to using it.
if ((isset($_POST['first_name'])) && (!empty( $_POST['first_name'])) ) {
//do query and rest of your script
} else { die('Need form input');}

Related

Inserting data into multiple different data tables

I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);

Issue with PHP and MySQL Database

Here is my main PHP code:
<?php
define('dbServer', 'localhost');
$dbUsername = 'root';
$dbPassword = '';
define('dbName', '1');
$dbConnection = mysqli_connect(dbServer, $dbUsername, $dbPassword, dbName);
if(!$dbConnection){
die("Unsuccessful Connection: " . mysqli_connect_error());
}
// All user data will be taken from the form //
$emailAddress = $_POST['emailaddress'];
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$streetAddress = $_POST['streetaddress'];
$phoneNumber = $_POST['phonenumber'];
$comments = $_POST['comments'];
$sql = "INSERT INTO user-submission (email, firstName, lastName, address, phoneNumber, comment) VALUES ('$emailAddress', '$firstName', '$lastName', '$streetAddress', '$phoneNumber', '$comments')";
$result = mysqli_query($dbConnection, $sql);
if (!$result){
die('Error: ' . mysqli_connect_error());
}
?>
My SQL database contains the rows ID, email, firstName, lastName, address, phoneNumber, comment. They are in a database called '1' (for testing purposes) and a table called 'user-submission'.
I have been unable to query this information into my table. I have been successful prior to this on other SQL and PHP pairings. What am I doing wrong this time?
Add this right below the opening php tag at the top then the server will tell you what the error is. Copy the error here if you need help decyfering
error_reporting( E_ALL );
First you need to make changes so hackers don't abuse your code.
Just wait till johnny;drop tables; comes by and wipes out your database.
// All user data will be taken from the form //
$emailAddress = mysqli_real_escape_string($dbConnections,$_POST['emailaddress']);
$firstName = mysqli_real_escape_string($dbConnections,$_POST['firstname']);
$lastName = mysqli_real_escape_string($dbConnections,$_POST['lastname']);
$streetAddress = mysqli_real_escape_string($dbConnections,$_POST['streetaddress']);
$phoneNumber = mysqli_real_escape_string($dbConnections,$_POST['phonenumber']);
$comments = mysqli_real_escape_string($dbConnections,$_POST['comments']);
$sql = "INSERT INTO `user-submission` (email, firstName, lastName, address, phoneNumber, comment) VALUES (?,?,?,?,?,?)";
$prep=$dbConnections->prepare($sql);
$prep->bind_param("ssssss",$emailAddress,$firstName,$lastName,$streetAddress,$phoneNumber,$comments);
#actually puts everything together, and puts it in the database
$prep-execute();

PHP mysql cannot insert data

// Do not put any echo code other than the last line.
// didnt include $con in the post.
$userlvlid = $_POST["userlvlid"];
$username = $_POST["username"];
$password = $_POST["password"];
$lname = $_POST["lname"];
$fname = $_POST["fname"];
$mname = $_POST["mname"];
$birthdate = $_POST["birthdate"];
$streename = $_POST["streetname"];
$province = $_POST["province"];
$city = $_POST["city"];
$barangay = $_POST["barangay"];
$organization_name = $_POST["orgname"];
$email_address = $_POST["email_address"];
$license = $_POST["license"];
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
else{
// means connection successful.
echo "sucess";
}
$response = array();
$response["success"] = false;
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// means username already exists.
}
else {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO accounts (`userlvlid`,
`username`,
`password`,
`lname`,
`fname`,
`mname`,
`birthdate`,
`streetname`,
`region`,
`province`,
`city`,
`barangay`,
`orgname`,
`email`,
`license`)
VALUES
('$userlvlid',
'$username',
'$password',
'$lname',
'$fname',
'$mname',
'$birthdate'
'$streetname',
'$region',
'$province',
'$city',
'$barangay',
'$organization_name',
'$email_address',
'$license')";
if (mysqli_query($con, $sql)) {
$response["success"] = true;
}
else {
}
}
}
echo json_encode($response);
?>
Can someone explain why "mysqli_query($con, $sql)" is returning false? I can't find what is wrong in the code. my database contains all of the fields and here maybe a syntax error. The code doesn't give me any errors and it doesn't add the information to the database.
A few things, first this part is not needed:
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// means username already exists.
}
Why? Because in between the time that you check for the user's existence and the time that you insert a new record, another client may create a user with the same username. So your second query the insert will fail if it happens (provided of course that you have a unique index on your username as you should).
Secondly, you are not escaping parameters. This leaves you open to SQL injection attacks. And it could also lead to malformed queries that do not get executed correctly - result data is not inserted. Use prepared statements instead.
$sql = mysqli_prepare($con,"INSERT INTO accounts (`userlvlid`,
`username`,
`password`,
`lname`,
`fname`,
`mname`,
`birthdate`,
`streetname`,
`region`,
`province`,
`city`,
`barangay`,
`orgname`,
`email`,
`license`)
VALUES
(?,?,?,?,?,?,?,?,?...)";
Then you need to bind the params
mysqli_bind_params($stmt,('$userlvlid',"ssssssssssssss",
$userlvlid
$username,
$password,
$lname,
$fname,
$mname,
$birthdate,
$streetname,
$region,
$province,
$city,
$barangay,
$organization_name,
$email_address,
$license));
Ugly isn't it? That's why one should use PDO instead of mysqli but using mysqli without prepared statements is just horrible so we have to slog through this.
Now while going through this copy paste, I discovered the real cause of your problem
'$mname',
'$birthdate' /*** no comma here ***/
'$streetname',
Try using echo for the $sql and place the exit after that statement. So that it breaks the query execution after that.
By doing this you can find whether any error is available in the query and you can rectify it.
Note: You first put echo to the Insert Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;
If you have any Table Column mismatch or and Data Discrepancy you can rectify with the help of this echoed query.
Ensure that you provide values that are matching the values that are given into the DB.
**Note: **(E.g) if userlvlid - varchar(11) - You should provide value which is equal to 11 or less than 11 if you enter the value greater than 11 it will not be inserting and the query will fail from there on.

Input values aren't being stored in a MySQL database

I've created a simple login form. I'm not able to store user input values at the back-end. Here's the full code for your reference:
dp.php
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'list') or trigger_error(mysqli_error());
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email_id'];
$password = $_POST['password'];
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES ('$first_name', '$last_name', '$email','$password')";
mysqli_query($dbc, $query) or trigger_error(mysqli_error($dbc));
echo 'login created';
mysqli_close($dbc);
?>
remove single quote from php variable
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES
($first_name, $last_name, $email,$password)";
if your data contain string that will put in "" or ''
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES
('".$first_name."','".$last_name."', '".$email."','".$password."')";
i hope this will solve your problem if $_POST get correct data . you have to concat string at that time

Shared login session between EasyAppointments and Bootstrap website

This is my first post on stackoverflow, though I have done extensive research using it along with other sources on a regular basis (including the subject I need help with here.)
To be concise, I am working on a shared session/login/register between a client's site and the EasyAppointments scheduling application. While compiling the config.php for the registration form on my client's site I received this error. I have searched everywhere, please help me understand this:
INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles) VALUES(testing, test, 000000000, 000000000, 123 example street, Birmington, Alabama, 00000, , )INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days) VALUES(TestUser, 0000000000, , , 0, , , , , )
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 ' , 0, , , , , )' at line 2
Here is my config.php code (please excuse my unorthodox variables for sql1/sql2):
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '####');
define('DB_USER','####');
define('DB_PASSWORD','####');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$mobile_number = $_POST['mobile_number'];
$phone_number = $_POST['phone_number'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip_code = $_POST['zip_code'];
$noteboy = $_POST['notes'];
$privs = $_POST['id_roles'];
$email = $_POST['email'];
$nick = $_POST['nick'];
$password = $_POST['password'];
$salt = $_POST['salt'];
$working_plan = $_POST['working_plan'];
$notifications = $_POST['notifications'];
$google_sync = $_POST['google_sync'];
$google_token = $_POST['google_token'];
$google_calendar = $_POST['google_calendar'];
$sync_past_days = $_POST['sync_past_days'];
$sync_future_days = $_POST['sync_future_days'];
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES($first_name, $last_name, $mobile_number, $phone_number, $address, $city, $state, $zip_code, $noteboy, $privs)";
echo $bang;
$banger = "INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days)
VALUES($nick, $password, $salt, $working_plan, $notifications, $google_sync, $google_token, $google_calendar, $sync_past_days, $sync_future_days)";
echo $banger;
$result = mysql_query($bang); mysql_query($banger);
if($result) {
echo "Successfully updated database";
} else {
die('Error: '.mysql_error($con));
}
mysql_close($con);
I doubt you're storing phone numbers as integers, so you should be quoting all those zeroes. SQL doesn't like missing values in the VALUES clause, so you need to fix that to default to a format that's appropriate for your fields, such as empty string, a zero or a NULL. You also need to think about escaping too to avoid errors and SQL injection vulnerabilities - using PDO might be good idea if you're early on in your project, and you should definitely switch to mysqli at the very least.
Your check for query failure only looks at your first query - you should check both.
Anyway, here's how you might apply escaping and quoting to avoid the error you're seeing using your current approach:
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES('".
mysql_real_escape_string($first_name)."','".
mysql_real_escape_string($last_name)."','".
mysql_real_escape_string($mobile_number)."','".
mysql_real_escape_string($phone_number)."','".
mysql_real_escape_string($address)."','".
mysql_real_escape_string($city)."','".
mysql_real_escape_string($state)."','".
mysql_real_escape_string($zip_code)."','".
mysql_real_escape_string($noteboy)."','".
mysql_real_escape_string($privs)."')";

Categories