I'm repeatedly getting a syntax error when inserting in to mysql, normally this works fine but I can't seem to get it to work. I can echo out the variables no problem but for some reason I can't insert them.
variables (the session vars are brought over from another page)
session_start();
$name=$_SESSION['bName'];
$email=$_SESSION['email'];
$ship_address = $_SESSION['sAddress'];
$voucher=$_SESSION['voucher'];
$sku=$_SESSION['sku'];
$credit_card=$_POST['credit_card'];
$security_code=$_POST['security_code'];
$payment_type=$_POST['payment_type'];
$cc_number=substr($credit_card, 0, 4) . str_repeat('x', (strlen($credit_card) - 4)) . substr($credit_card, -4, 4);
$phone=$_SESSION['billPhone'];
$status="Redeemed";
$date = date('Y/m/d');
$tracking ="";
insert query
//Insert Queries
$sqlInsert = "INSERT INTO `customers`(`name`, `email`, `address`, `phone`, `sku`, `creditcard`, `securitycode`, `paymenttype`, `voucher`, `purchase_id`, `tracking`, `status`, `date_recieved`)
VALUES( $name, $email, $ship_address, $phone, $sku, $credit_card, $security_code, $payment_type, $voucher, $purchase_id, $tracking, $status, $date)";
mysql_query($sqlInsert) or die ('Error Inserting into database' . mysql_error());
I've also tried
VALUES( '$name', '$email', '$ship_address', '$phone', '$sku', '$credit_card', '$security_code', '$payment_type', '$voucher', '$purchase_id', '$tracking', '$status', '$date')
but it doesn't work. The error I get is
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 'lastname, fahad#semail.com, 22 toronto ont l6a0l4, 416-123-4567, 1001234, 1234567' at line 1
Any ideas?
Thanks
all string values must be quoted.
VALUES("'.$name.'", "'.$email.'" ...
Do it like this, so the fields are delimited:
VALUES( '$name', '$email', ...
check your error message to see what kind of garbage you are currently generating.
You could use PDO to create prepared statements instead. Then you won't have to worry about escaping your values like drdwilcox's example 'Jerry''s'. It also helps as a counter measure against SQL Injection attacks.
I would almost guarantee that you have a single-quote in your name field. If you want to place a single quote into a string field in SQL, you must double it: 'Jerry''s'
And you need the '$name' version.
Related
Im having a problem with my PHP code, it says the error is "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"
It connects to the database ok as it echos "Database Connection Successful" but it dosnt insert the data into the database. This worked fine before, but now all of a sudden its stopped working. Can anyone help?
<?php
$username = "student";
$password = "student";
$hostname = "localhost";
$db = "details";
$link = new mysqli($hostname, $username, $password, $db);
if ($link->connect_errno)
printf("Connect failed: %s\n", $link->connect_error);
else
echo "Database Connection Successful \n";
echo nl2br("\n");
$Urgency = "Urgency";
if(isset($_POST['submit'])){
$TypeOfProblem = $_POST['problemtype'];
$ProblemDescription = $_POST['problem'];
$RoomNo = $_POST['roomno'];
$Problem = $_POST['reporter'];
$Urgency = $_POST['Urgency'];
$Date = $_POST['date'];
//Insert into Database
$sql = "INSERT INTO `details`.`problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`,`Date` ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
if (!mysqli_query($link, $sql))
{
die('Error: ' . mysqli_error($link));
}
echo "\n Thank you. Your Helpdesk Call has been submitted.";
mysqli_close($link);
}//////// end isset submit if ////////
?>
Thanks
Try using this, the problem is the single quote ` should be '
$sql = "INSERT INTO 'details'.'problem' ('Type Of Problem', 'Problem Description', 'RoomNo', 'Urgency', 'UserIDProblem','Date' ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')"
Or try to set an echo $sql and test the query directly on de dbms
The date '$Problem', $Date)"; needs single-quotes '$Problem', '$Date')";
First, it is a good idea to leave out the database name:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
Are you sure, that your column names have spaces in it? I mean this would work, but this is not a good idea, I think.
I cannot find another problem in your query, maybe you should quote the date:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')";
Otherwise, please provide us with the full query:
die("INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)");
And you SHOULD notice, that your code is exploitable with SQL-Injections! Use mysqli_real_escape_string.
For debugging this, output the actual SQL text that is being submitted to the database, using echo or vardump e.g.
$sql = "INSERT INTO ...";
echo "SQL=" . $sql ;
That will show you the actual statement that's going to be submitted to the database, and you can usually debug the problem from there.
If date isn't a numeric, if it represents a DATE datatype or a string, the value needs to be enclosed in single quotes. Otherwise, it's likely going to be interpreted in a numeric context.
Note that this code appears to be vulnerable to SQL Injection, because it includes potentially unsafe values in the SQL text. Consider what happens when a value contains "special" characters, like a single quote, or comma.
Potentially unsafe values must be properly escaped. With mysqli, you can use the mysqli_real_escape_string function.
A better pattern is to use a prepared statement with bind placeholders.
As an example of what that would look like (before it's cluttered up with code to checks for errors from the return of the mysqli_ function calls)
$sql = "INSERT INTO `details`.`problem`
(`Type Of Problem`,`Problem Description`,`RoomNo`,`Urgency`,`UserIDProblem`,`Date`)
VALUES (?,?,?,?,?,?)";
$sth = mysqli_prepare($link,$sql);
if (!$sth) {
echo "error:" . mysqli_error($link);
)
mysqli_stmt_bind_param($sth,"ssssss"
,$TypeOfProblem,$ProblemDescription,$RoomNo,$Urgency,$Problem,$Date);
mysqli_stmt_execute($sth);
$bzSendMail = mysqli_query($Connection, "INSERT INTO messages_inbox (from, towho, subject, text, rcvdat) VALUES ('$MyID', '$SenderID', '$subject', '$text' ,'$sentat')");
I'm trying to make this query works, but it keeps showing me the following 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 'from, towho, subject, text, rcvdat) VALUES ('1', '2', 'd', 'd' ,'2014-09-07 17:0' at line 1
Anyone can help me?
you are using
FROM
as a column name in your table. You can use '' to specify the column name but it is always better not to use that kind of names as your column names.
$bzSendMail = mysqli_query($Connection, "INSERT INTO messages_inbox (`from`, `towho`, `subject`, `text`, `rcvdat`) VALUES ('$MyID', '$SenderID', '$subject', '$text' ,'$sentat')");
From is a key word in Mysql use backward quotes to skip this as follows
$bzSendMail = mysqli_query($Connection, "INSERT INTO messages_inbox (`from`, `towho`, `subject`, `text`, `rcvdat`) VALUES ('$MyID', '$SenderID', '$subject', '$text' ,'$sentat')");
from is a reserved word in sql. Make backticks around it.
This question already has answers here:
MySQL, safely using reserved word in query [duplicate]
(2 answers)
Closed 9 years ago.
I am building a small Twitter clone for personal use, and I have so trouble with it.
Fist, I want to show you my SQL structure of the table "poke_history":
http://puu.sh/3Sci0.png
This is the command I use to insert the values into a table (in PHP):
$insert = "INSERT INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
This is the annoying error that I am getting:
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 'from, time, reason) VALUES ( '1'' at line 3.
Let me clarify some things.
$to_id is a number.
$from_id is a number.
$time is a number (coming from PHP's time()).
$reason is a text string.
I am using MySQL and PHP5.
Try to quote your column identifiers like
INSERT INTO poke_history (`id`, `from`, `time`, `reason`) ...
Everything inside `` is considered to be a "identifier" not a language keyword. From the SQL-syntax it should be clear that after INSERT INTO tablename cannot come a FROM, but the MySQL sometimes needs this kind of guidance (and other sql parsers, too).
credit to mario as well:
from is a reserved keyword. Use backticks to escape them.
for example
`from`
INSERT INTO table (`from`) ....
So your code would like this:
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES (".$to_id.", ".$from_id.", ".$time.", '".$reason."')";
mysql_query($insert) or die(mysql_error());
Numbers don't need to be quoted. Only strings.
Also don't use mysql, it's deprecated. Better use PDO, with prepared statements, to avoid issues like this.
You should try to use prepared statements to prevent SQL injection.
$query = "
INSERT INTO
poke_history (`id`, `from`, `time`, `reason`)
VALUES
(:id, :from, :time, :reason)";
$db = new PDO("mssql:host=sqlserver;dbname=database", "username", "password");
$statement = $db->prepare($query);
$parameters = array(
":id" => $name,
":from" => $from,
":time" => $time,
":reason" => $reason
);
$statement->execute($parameters);
I think that you forgot to add * in between INSERT and INTO, here is the fixed script:
$insert = "INSERT * INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
The reason why you are getting the error is because you are trying to use a built in function name for one of your columns. Say you have the following CREATE TABLE...
CREATE TABLE customers
(
name varchar(80),
streetAddr varchar(160),
"from" varchar(60),
);
Notice that to create the table I had to put the column from in quotes. Now if you wanted to insert a row into this table, your insert statement should look like the following:
INSERT INTO ShoppingFun.dbo.customers
(
name,
streetAddr,
"from"
)
VALUES
(
'MRBubbleGum',
'1061 SW BubbleGumVillage St',
'yourmom'
)
There's gotta be something small I keep missing here, but I can't find it for the life of me.
$insert = mysql_query("INSERT INTO USERS
(`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES ('$fbid', '$firstName', '$lastName', '$gender')");
The error is:
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 '1' at line 1
Any ideas?
You are not having variables correctly escaped. Use mysql_real_escape_string and code like this:
$insert = mysql_query("INSERT INTO USERS (`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES (
'".mysql_real_escape_string($fbid)."',
'".mysql_real_escape_string($firstName)."',
'".mysql_real_escape_string($lastName)."',
'".mysql_real_escape_string($gender)."'
)");
If the variables contain any quotes, they create the problem if you don't properly escape them.
Do any of your names contain single quotes?
Try writing out the value of the query to log/console/debug to ensure that it's what you expect.
Try wrapping your variables in {}.
'{$fbid}', '{$firstName}', '{$lastName}', '{$gender}'
Otherwise you are going to have to use string concatenation.
'".$fbid."','".$firstName."','"...
I'm assuming your variables already contain proper escaped data.
Try doing it like this:
$sql = <<EOL
INSERT INTO USERS (`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES ('$fbid', '$firstName', '$lastName', '$gender')
EOL;
$stmt = mysql_query($sql) or die("MySQL error: " . mysql_error());
This will preserve the query for you in $sql so you can echo it out elsewhere and see what was actually produced.
I have this query running in my PHP script:
$insertQuery = "INSERT INTO blog_articles
VALUES '$title', $tags', '$category', '$blog', '$author', '$date'";
I then run this script:
if ($result = $connector->query($insertQuery)){
// It worked, give confirmation
echo '<center><b>Article added to the database</b></center><br>';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
die (mysql_error());
}
}
I get 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 'Title Number 1, General, Blogging, Kayaking, General, Tgis is blog number spelli' at line 2
But I cannot tell what the error is.
You have a single quote missing before $tags.
Your query should be more like this
INSERT INTO blog_articles (`title`, `tags`, `category`, `blog`, `author`, `date`)
VALUES ('$title', '$tags', '$category', '$blog', '$author', '$date')
You should also look into sanitizing your query. Perhaps this way (but i don't know your exact setup, so results might vary)
$sql = sprintf("INSERT INTO blog_articles (`title`, `tags`, `category`,
`blog`, `author`, `date`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($title), mysql_real_escape_string($tags),
mysql_real_escape_string($category), mysql_real_escape_string($blog),
mysql_real_escape_string($author), mysql_real_escape_string($date));
This uses the sprintf() function, the php documentation has some great examples.
You need to add the names of the fields you are inserting to
INSERT INTO blog_articles ('title', 'tags', 'category', 'blog', 'author', 'date') VALUES ('$title', '$tags', '$category', '$blog', '$author', '$date')
Also you should add some code to escape double or single quote in your text that could break the SQL query.
use the PHP function mysql_real_escape_string()
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
For more details:
http://uk.php.net/mysql_real_escape_string
As aknock says, you are missing a ' before $tags.
However, you really need to be using mysql_escape_string to protect against SQL injection attacks. Using mysql_escape_string for your SQL query parameters is a good habit to get into.
Using a DB wrapper like PEAR can make escaping parameters much less painful. Your code above could be written like:
$insertQuery = "INSERT INTO blog_articles \
(`title`, `tags`, `category`, `blog`, `author`, `date`) \
VALUES (?, ?, ?, ?, ?, ?)";
$data = array($title, $tags, $category, $blog, $author, $date);
if ($result = $connector->query($insertQuery, $data)) {
// It worked, give confirmation
echo '<center><b>Article added to the database</b></center><br>';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
die (mysql_error());
}
(assuming $connector is a PEAR DB object)
Explicitly giving the names and order of the columns that you're inserting makes your code much more maintainable and readable. If you change the database schema later, you will be protected from inserting values into the wrong column, or into columns that don't exist any more.