Recently I'm getting an error message that I don't know how to deal with. It's very vague.
The PostgreSQL statement I use is:
$result = pg_query($ruledbconnection, "INSERT INTO INPUT(num, pkts, bytes ,
target,prot, opt, \"in\", out, source, destination, id)
VALUES('$num','$bytes','$pkts','$target', '$opt', '$protocol', '$in', '$out',
'$source', '$destination', '$id')");
All seems fine, right? However, when I execute this query with variables:
ERROR: syntax error at or near "'INPUT'" LINE 1: INSERT INTO 'INPUT'(num, pkts, bytes ,
target, prot, opt, "i... ^
I've been stuck on this for a while and it might be due escaping in PHP, or maybe something else?
The table that I want to manipulate is called INPUT in my database..
The SQL you showed doesn't match the error. The SQL doesn't have quotes around the table name, the error does.
ERROR: syntax error at or near "'INPUT'" LINE 1: INSERT INTO 'INPUT'(num, pkts, bytes ,
So. Single quotes (apostrophes, ') are for SQL values, not identifiers. Identifiers are quoted with double quotes ("). So you'd write:
INSERT INTO "INPUT" (...) VALUES (...)
Note that quoting the table name will preserve case. So if you double quote it here, you must double quote it everywhere you refer to it from. You will save your sanity if you instead just use lower case:
INSERT INTO input (...) VALUES (...)
and even better, a descriptive table name:
INSERT INTO packets_received (...) VALUES (...)
Your syntax error is the least of your problems, though. Let me introduce you to a classic:
Your query follows the pattern:
pg_query($conn, 'INSERT INTO sometable (col) VALUES ($user_input)')
and thus, is a classic example of an SQL injection vulnerability.
Read:
Bobby Tables
PHP manual on SQL injection
Solved by making sure that I escape the quotes around my table name.
"INSERT INTO INPUT (num, pkts, bytes , target, prot, opt, \"in\", out, source, destination, id)
Should be:
"INSERT INTO \"INPUT\" (num, pkts, bytes , target, prot, opt, \"in\", out, source, destination, id)
Related
I have a necessity to insert some record from one table1 in database1 to another table2 in database2.
So far I have this..
$records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `export` WHERE ID < 100"));
$columns_r = implode(",",array_keys($records_r));
$values_r = implode(",",array_values($records_r));
$import = mysqli_query($conn_i,"INSERT INTO NOTimport ($columns_r) values ($values_r)");
if (!$import) {
printf("Error: %s\n", mysqli_error($conn_i));
exit();}
It gives me the error:
Error: You have an error in your SQL syntax;
This is how the syntax looks:
INSERT INTO `NOTimport` ('xx,xx,xx,xx,xx,xx,xx,xx') values ('11,'11,E,2079,1931,xx,xx,x')
I am 99% sure that single quotes are causing the error, but why are there?
As per your original post https://stackoverflow.com/revisions/31116693/1 and completely overwriting your original post without marking it as an edit:
You're using the MySQL import reserved word
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
It needs to be wrapped in ticks
INSERT INTO `import` ($columns_r) values ($values_r)
or rename that table to something other than a reserved word.
Plus, $values_r may require to be quoted and depending on what's being passed through $columns_r, you may need to use ticks around that.
I.e.:
INSERT INTO `import` (`$columns_r`) values ('".$values_r."')
Even then, that is open to SQL injection.
So, as per your edit with these values values ('11,'11,E,2079,1931,xx,xx,x'), just quote the values since you have some strings in there. MySQL will differentiate between those values.
Escape your values:
$values_r = implode(",",array_values($records_r));
$values_r = mysqli_real_escape_string($conn_r, $values_r);
or $conn_i I'm getting confused as to which variable is which here. Be consistent if you're using the same db.
Edit:
As stated in comments by chris85, use prepared statements and be done with it.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
import is a reserved word in MYSQL. So, you need to use backticks (``) around it in your query.
So rewrite as follows:
$import = mysqli_query($conn_i,"INSERT INTO `import` ($columns_r) values ($values_r)");
Without Using PHP you can use MySql Query Which Will Perform Insert Operation As:-
$columns_r='`name`,`class`';
mysqli_query($conn_i,"INSERT INTO `import` ({$columns_r}) select {$columns_r} from `export`");
Getting really confused surrounding this INSERT INTO. It should insert three fields into the table, userID, activateKey and isActivated.
The activateKey is a 25 letter randomly generated key such as 63n20kw24ba1mlox34e8n2awv
The userID comes from another table and is set by auto_increment.
The isActivated is always 0 at this stage.
It seems like quite a simple INSERT statement
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
{
echo("Error description: " . mysqli_error($con));
}
However it doesn't work when I include the $activateKey field. What it does is try to search the string variable $activateKey as a column name. The error I get is:
Error description: Unknown column '63n20kw24ba1mlox34e8n2awv' in 'field list'
Of course there is no such column as 63n20kw24ba1mlox34e8n2awv, this is the data I'm trying to insert, hence why it's in the VALUES section. Any ideas why it's trying to search this as the column name?
Edit to clarify: the var is activateKey, the column name is activationKey
I would put the query in a different variable to avoid confusion, and PHP automatically substitutes variable names in strings in double quotes.
Try this:
<?php
$query = "INSERT INTO activations (userID,activationKey,isActivated) VALUES($userID,'$activateKey','0')
if (!mysqli_query($con,$query)
{
echo("Error description: " . mysqli_error($con));
}
You are not surrounding the values with quotes, that's why they get interpreted as variable names.
Use single quotes, like this:
"INSERT INTO activations (userID,activationKey,isActivated) VALUES
('".$userID."','".$activateKey."','0')"
However, be aware that stringing together query strings exposes you to SQL injection attacks, if that's a concern in your code you should use parameterized queries. In fact, using parameterized queries is always better.
Change your query to this:
"INSERT INTO activations
(userID,activationKey,isActivated)
VALUES ('$userID','$activateKey','0')"
You dont need to use the concatenation (.) operator as variables will be interpolated into the string.
The single quotes tell mysql to treat the variables as literals instead of column names.
As a side note you would be better to use parameterized queries. See How can I prevent SQL injection in PHP?
Solved!
It was a case of not properly wrapping the dynamic fields (the vars in the VALUES section) in ticks:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES ('".$userID."','".$activateKey."','0')"))
Instead of
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
Might be a difficult one to spot. The variables still need to be 'in ticks' or they won't register as strings.
As activationKey is a string column, you must use single quotes for $activationKey.
Try with:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated)
VALUES (".$userID.",'".$activateKey."','0')"))
Ok its late and I am not catching why this is broken. So here goes.. the error is as follows
syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING
or T_VARIABLE or T_NUM_STRING
typically I would assume its a mising ; ' " or similar, I've checked I have found nothing missing from the surrounding code.
Now despite the possible "injection" factors which I don't care about currently someone please tell me whats wrong with this one line.
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, $when, $email, $fakeHash, '0', mysql_real_escape_string($_POST['fileID']))") or die(mysql_error());
Besides using a quoted subscript on an embedded (interpolated) variable, you are likely missing some quotes (around values) in the query.
Try this:
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, '".mysql_real_escape_string($when)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($fakeHash)."', '0', '".mysql_real_escape_string($_POST['fileID'])."')") or die(mysql_error());
If the $_POST['fileID'] is always expected to be an integer, then it does not need to be wrapped in a mysql_real_escape_string call and it would actually be safer (against SQL injection) and possibly more efficient to just cast it to an int:
mysql_query("INSERT INTO files_posted (ID, when, email, randomkey, count, fileID) VALUES (NULL, '".mysql_real_escape_string($when)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($fakeHash)."', '0', ".((int)$_POST['fileID']).')') or die(mysql_error());
One of your variables contains an apostrophe:
$when, $email, $fakeHash
That's my guess. You should use mysql_real_escape_string() for all of those.
Make sure you enclose all text field values in (single or double) quotes (and make sure they are escaped). The quotes are required to make sure MySQL treats the text as strings and not as something else.
Alternatively, use PDO, and you don't have to worry about that.
mysql_query("INSERT INTO dictionary ('word', 'definition') VALUES ('".$word."','".$definition."');")
That just will not execute, when I echo it - I get this:
INSERT INTO dictionary ('word', 'definition') VALUES ('monkey','monkey');
So the values are being brought into it properly, if I out put mysql_error() I get:
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 ''word',
'definition' VALUES
('monkey','monkey')' at line 1
Any ideas? I'm stumped.
You need to use backticks for field names:
INSERT INTO dictionary (`word`, `definition`)
(or, of course, no quotes at all. But it is better to have them.)
Yeh remove the quotes from the column definitions. You only need them around the strings you are inserting.
When referencing column names for INSERT you should be using backticks (`) not single quotes. (Single quotes is telling MySQL those values are strings and not column references).
Either remove the single quotes or use the backticks and the problem should resolve itself.
Change your single quotes around word and dictionary to backticks:
INSERT INTO dictionary (`word`, `definition`) VALUES ('monkey','monkey');
Correct Method:
mysql_query("INSERT INTO `dictionary` (`word`, `definition`) VALUES ('".$word."','".$definition."');")
which will be ouput as this:
INSERT INTO `dictionary` (`word`, `definition`) VALUES ('monkey','monkey');
if this is not working:
mysql_query("INSERT INTO dictionary (word,definition) VALUES ('".$word."','".$definition."')");
then you have problem with field names... check your name in table... or maybe you missing something! what your table look like?
mysql_query("INSERT INTO dictionary (`word`, `definition`) VALUES ('".$word."','".$definition."');")
Note the apostrophes. The field names should either use no apostrophes, or use the ones shown here.
I'm by no means experienced in mysql and keep getting an error in this lines of code:
$sql= "INSERT INTO songs (unique_show_id, artist, date, year, city, state, venue, taper, transfered_by, source, mic_loc, lineage, uploaded_by, uploaded_on, show_notes, show_xml)
VALUES('$showId', '$artist', '$showDate', '$year, '$city', '$state', '$venue', '$taper', '$transferer', '$source', '$mic_loc', '$lineage', '$uploader', NOW(), '$show_notes', '$show_xml')";
//check to see if the query went through
if (!mysql_query($sql,$con)){
echo "query fail";
die('Error: ' . mysql_error());
}
I'm sure it's something simplistic, but I can't see where the error is. The error message I get is:
query failError: 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 'ipuhgbi', 'CA', '', '', '', '', '', '', 'danwoods', NOW(), '', '<show id=\'gm198' at line 2
Some of the values I'm inserting are NULL, but from what I've read I don't think that should be a problem. Any ideas?
Missing quote after $year.
When MySQL issues such an error (near bla di bla), the error is usually immediately before the string it mentions. In this case 'ipuhgbi' maps to $city, so you know it's right before '$city', and what do we see there? Voila, a missing quote.
You need to use mysql_real_escape_string() in each and every single one of your $variables.
Also, read this StackOverflow question carefully regarding SQL Injections.
It looks like the last single quote on the error line is not escaped.
you need to remember to sanitize all of the strings going into the query.
There are quite few things you need to be sure about:
You don't insert primary keys through queries (eg unique_show_id in your code)
For numbers you don't use single quotes.
It is better to use the set variant of inserting records which avoids count problems eg:
Use intval for numbers and mysql_real_escaps_string for strings to avoid injections issues as well as single quotes query erros.
insert into table set field='field_value', field2='field_value' // and so on