i am getting this error:
SQLSTATE[42000]: Syntax error or access violation: 1064 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 'INSERT INTO student_details (student_id, first_name, last_name, dob, address_lin' at line 2
for this code: any idea?
//create variables from each value that was submitted from the form */
$student_info_id = $_POST['student_info_id'];
$class_id = $_POST['class_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$dob = $_POST['dob'];
$address_line_1 = $_POST['address_line_1'];
$address_line_2 = $_POST['address_line_2'];
$town = $_POST['town'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
$gender = $_POST['gender'];
$ethnicity = $_POST['ethnicity'];
try {
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $password);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "
INSERT INTO student_info (student_info_id, class_id) VALUES (:student_info_id, :class_id)
INSERT INTO student_details (student_id, first_name, last_name, dob, address_line_1, address_line_2, town, county, postcode, gender, ethnicity, student_info_id)
VALUES (:student_id, :first_name, :last_name, :dob, :address_line_1, :address_line_2, :town, :county, :postcode, :gender, :ethnicity, :student_info_id)
";
$statement = $conn->prepare($sql);
$statement->bindValue(":student_info_id", $student_info_id);
$statement->bindValue(":class_id", $class_id);
$statement->bindValue(":student_id", $student_id);
$statement->bindValue(":first_name", $first_name);
$statement->bindValue(":last_name", $last_name);
$statement->bindValue(":dob", $dob);
$statement->bindValue(":address_line_1", $address_line_2);
$statement->bindValue(":address_line_2", $address_line_1);
$statement->bindValue(":town", $town);
$statement->bindValue(":county", $county);
$statement->bindValue(":postcode", $postcode);
$statement->bindValue(":gender", $gender);
$statement->bindValue(":ethnicity", $ethnicity);
$statement->bindValue(":student_info_id", $student_info_id);
$count = $statement->execute();
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
I'm not sure if PDO support multiple statements, but if so, the error is that you did not terminate the first statement,
INSERT INTO student_info (student_info_id, class_id)
VALUES (:student_info_id, :class_id);
^ add this one
You'll have to finish the first INSERT with a ; Like this:
INSERT INTO student_info (
student_info_id,
class_id
) VALUES (
:student_info_id,
:class_id
); <-- a semicolon is the default statement separator, use it
....
Note that, although it is possible to run multiple queries at once, I would not advice you to do it. If you would run each query one by one you would have a better control over errors.
You can't run multiple queries in one call.
Run them separately, one by one.
Related
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');}
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)."')";
I have a weird error, using MyPhpAdmin, I added a row, and the script it generates is:
INSERT INTO 'Users'.'User_Accounts'('Account_ID', 'UserName',
'Email', 'PhoneNumber', 'Password') VALUES (NULL, 'fdsfsadf',
'dfsadf', 'sdfads', 'fsdfasdfsd');
That works, however when I use PHP PDO to insert it gives this error:
Table 'Users.User_Acounts' doesn't exist
uhhhh yes it does...
The PHP code:
$hostname = "127.0.0.1";
$port = "3306";
$database = "Users";
$username = "AccountControl";
$password = "w67hLAanWESGNJMC";
echo ">>";
$db = new PDO("mysql:host=$hostname; port=$port; dbname=$database", $username, $password);
echo ">>";
$UserName = "KiteDev";
$Email = "johndoveail.com";
$PhoneNumber = "66666";
$Password = "dfsgetagfdasg";
// Create the query
$query = "INSERT INTO User_Acounts (UserName, Email, Phon2eNumber, Password) VALUES (:name, :email, :phone, :pass )";
// Prepare statement with $stmt variable
$stmt = $db->prepare($query);
echo ">>";
// Bind parameters, (you can also remove the PDO::PARAM_INT)
$stmt->bindParam(':name', $UserName, PDO::PARAM_STR);
$stmt->bindParam(':email', $Email, PDO::PARAM_STR);
$stmt->bindParam(':phone', $PhoneNumber, PDO::PARAM_STR);
$stmt->bindParam(':pass', $Password, PDO::PARAM_STR);
// Execute the query once you're done binding all the params
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
echo ">>";
Any ideas as to what's causing this?
You've misspelled User_Accounts. The table you created is User.User_Accounts but the table that doesn't exist is User.User_Acounts.
You wrote accounts with one c
Table 'Users.User_Acounts' doesn't exist
The Table Name is User_Accounts. In your php code, it is misspelled as User_Acounts
Correct it as
$query = "INSERT INTO User_Accounts (UserName, Email, Phon2eNumber,
Password) VALUES (:name, :email, :phone, :pass )";
trying to setup a warranty registration page for a friends company and I'm not great at Mysql or PHP (Read: Noob). I've scoured the web for answers and have tried several variations to the code below with no success.
I have the table setup with the matching column names. The form submission is also setup correctly I believe.
Just not certain as to what is stopping it from actually posting the data to the database. Any help would be greatly appreciated.
Here's my post code.
<?php
error_reporting(-1);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$ordernumber = $_POST['ordernumber'];
$receivedate = $_POST['receivedate'];
$placeofpurchase = $_POST['placeofpurchase'];
$newsletter = $_POST['newsletter'];
?>
<?php
$con = mysqli_connect("localhost","DB_Username","PASSWORD","DB_NAME");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = ("INSERT INTO warrantyregistration (firstname, lastname, address, city, state, zipcode, country, phone, email, ordernumber, receivedate, placeofpurchase, newsletter)
VALUES
($firstname, $lastname, $address, $city, $state, $zipcode, $country, $phone, $email, $ordernumber, $receivedate, $placeofpurchase, $newsletter)");
if (mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Success!";
mysqli_close($con)
?>
Change this line:
if (mysqli_query($con,$sql))
to:
if (!mysqli_query($con,$sql))
and you should see an error message.
You got the wrong syntax for the SQL statement. You have to set your Php variables into ´$variable´
See my working code here:
insert into user
(
userid,
signedin_at,
)
values
(
'$vp_userid',
now()
);
You should be paramaterizing your queries and using prepared statements. This would protect you from the SQL injection and fix your issues. An abridged version of what you need to do is:
$stmt = mysqli_prepare($con, "INSERT INTO warrantyregistration
(firstname, lastname, address) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, "sss", $firstname, $lastname, $address);
mysqli_stmt_execute($stmt);
I got the same error. Without the paramaterizing you can fix that error in your sql statement:
...
$sql = "INSERT INTO warrantyregistration VALUES ($firstname, $lastname, $address, $city, $state, $zipcode, $country, $phone, $email, $ordernumber, $receivedate, $placeofpurchase, $newsletter)";
...
I am using following code to insert a row in database. I always get ERROR
{"error":"SQLSTATE[42000]: Syntax error or access violation: 1064 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 'show) VALUES('A E Jewelers','Quintin','Schmidt','131 South Rolling Meadows Dr.',' at line 1"}
Here is my query
xxx/webservice/api.php?action=addStore&name=A%20E%20Jewelers&firstname=Quintin&lastname=Schmidt&address=131%20South%20Rolling%20Meadows%20Dr.&city=Fond%20du%20Lac&state=WI&country=USA&zip=54935&phone=(920)%20933%203601%0A&fax=(920)%20486-1734&email=Diadori#aejewelers.com&latitude=43.775931&longitude=-88.482894&website=www.aejewelers.com&show=1
function AddStore()
{
$name = trim($_REQUEST['name']);
$firstname = trim($_REQUEST['firstname']);
$lastname = trim($_REQUEST['lastname']);
$address = trim($_REQUEST['address']);
$city = trim($_REQUEST['city']);
$state = trim($_REQUEST['state']);
$country = trim($_REQUEST['country']);
$zip = trim($_REQUEST['zip']);
$phone = trim($_REQUEST['phone']);
$fax = trim($_REQUEST['fax']);
$email = trim($_REQUEST['email']);
$latitude = trim($_REQUEST['latitude']);
$longitude = trim($_REQUEST['longitude']);
$website = trim($_REQUEST['website']);
$show = 1;
return $show;
$insert_id = 0;
try {
$conn = $this->GetDBConnection();
$statement = $conn->prepare('INSERT INTO stores( name, firstname, lastname, address, city, state, country, zip, phone, fax, email, latitude,longitude, website,show) VALUES(:name,:firstname,:lastname,:address,:city,:state,:country,:zip,:phone,:fax, :email, :phone, :zip)');
$statement->bindParam(':name', $name, PDO::PARAM_STR);
$statement->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$statement->bindParam(':lastname' , $lastname, PDO::PARAM_STR);
$statement->bindParam(':address', $address, PDO::PARAM_STR);
$statement->bindParam(':city', $city, PDO::PARAM_STR);
$statement->bindParam(':state', $state, PDO::PARAM_STR);
$statement->bindParam(':country', $country, PDO::PARAM_STR);
$statement->bindParam(':zip', $zip, PDO::PARAM_STR);
$statement->bindParam(':phone', $phone, PDO::PARAM_STR);
$statement->bindParam(':fax' , $fax, PDO::PARAM_STR);
$statement->bindParam(':email' , $email, PDO::PARAM_STR);
$statement->bindParam(':latitude' , $latitude, PDO::PARAM_STR);
$statement->bindParam(':longitude', $longitude, PDO::PARAM_STR);
$statement->bindParam(':website' , $website, PDO::PARAM_STR);
$statement->bindParam(':show' , $show, PDO::PARAM_INT);
$statement->execute();
$insert_id = $conn->lastInsertId();
$conn = null;
} catch(PDOException $e) {
throw $e;
}
return $insert_id;
}
Replace the column name show with `show`
INSERT INTO stores(
name, firstname, lastname, address, city, state,
country, zip, phone, fax, email, latitude,longitude,
website,`show`)
VALUES (:name,:firstname,:lastname,:address,:city,
:state,:country,:zip,:phone,:fax, :email,
:phone, :zip)'
The word show is a keyword in SQL
It's good practice to always wrap field names and table names in backticks ` to prevent this common "gotcha" with accidentally using a reserved keyword. There are an amazing number of reserved words in SQL, so it's probably easier just to backtick names rather than remembering to check each field or table name used.
I take it you have confirmed that none of the values are empty/null or have embedded spaces, quotes, or commas? Does the PDO library take care of escaping quotes (e.g., Mrs. O'Leary's Cow) and wrapping the data in quotes?