Why won't my SQL work? - php

I keep getting 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 ''food' ORDER BY 'id'' at line 1
How do i fix it?
<?php
require '113-connect-db.php';
$query = "SELECT * FROM 'food' ORDER BY 'id'";
if ($query_run = mysql_query($query)){
echo 'query successful';
} else {
echo mysql_error();
}
?>

If you want to escape table/column names in a query to MySQL, you need to use backticks, not apostrophes. Apostrophes are used to indicate string literals.
Instead of this:
SELECT * FROM 'food' ORDER BY 'id'
You would use this:
SELECT * FROM `food` ORDER BY `id`
But, in fact, that's an escape sequence that's only required for identifiers that are also MySQL keywords, or that will otherwise confuse the parser. The query you've shown could be written without them.

quotes are not used. use backticks. `
no need for backticks for table names and column names as long as they are not keywords.
$query = "SELECT * FROM food ORDER BY id";

Use backticks (`) instead of single quotes around the table name.

Remove the single quotes around the table name and the column name in the order by clause!

Single quotes ('...') mean a literal string in SQL, a sequence of characters of type char.
To name objects with case-sensitive names, special characters inside names keyword-clashing names, etc, double quotes ("...") are generally used. Specifically MySQL accepts backquotes `` in this role.
You cannot select from a string, obviously.

Sorry...could not see your code since now.
Is your connection up? If yes, try to remove ' and please check if the column "id" really exists.

Related

difference between ' single quote and ` backtick for mysqli_query

This is bizarre, I'm changing some code from mysql to mysqli functions cause of php 5.5+, in these two basic examples, mysql_query had no ' single quote nor ` backtick and worked fine.
$sql = "SELECT * FROM `".$table."`"; // requires: ` ` or fails
$result = mysqli_query($con,$sql);
$sql = "SHOW TABLES LIKE '".$table."'"; // requires: ' ' or fails
$result = mysqli_query($con,$sql);
Can someone explain why?
EDIT: I guess the essence of my question is that: Both functions worked fine without any kind of quotes with mysql_query, and both failed mysqli_query without some kind of quotes. Meaning I will have to fiddle around with half my query's when changing from mysql_ to mysqli_
In your first select statement you are trying to select a table by it's name, hence it will accept the name either with ` or without them, but now with single or double quotes. These should work :
$sql = "SELECT * FROM `table_name`";
$sql = "SELECT * FROM table_name";
In the second case you need to pass in a string to be compared by the like statement hence you need to surround it either with single ' or double " quotes:
$sql = "SHOW TABLES LIKE 'string'";
$sql = "SHOW TABLES LIKE \"string\"";
Edit:
Check out this previous answer on SO as well:
Using backticks around field names
Edit 2:
Since we (me and in comments) suggested that backticks are somehow optional, keep in mind that as a best practise use them whenever you can since although it will allow you to pass most queries without them, some queries using MySql reserved words would break when containing mysql reserved words

MySQL insert with multiple fields and where clause

I'm trying to construct a query for a cron that will run.
mysql_query("UPDATE `stocks` SET price='$pricez', open='$openz', high='$highz', low='$lowz', change='$changez', time='$times', percent='$percentz' WHERE symbol = '$symbolz' ");
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 'change='-0.10', time='1406050151', percent='-0.35%' WHERE symbol = 'ALMB.CO'' at line 1
Scavenged SOF and have yet to find a solution.
Reserved words just bit you:
Change is a reserved word thus needs to be escaped: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
mysql_query("UPDATE `stocks` SET price='$pricez', open='$openz', high='$highz',
low='$lowz', `change`='$changez', time='$times', percent='$percentz' WHERE symbol = '$symbolz' ");
So what is a reserved word?
They are words the engine uses to interpert specific requested commands. When these words are used as identifiers for tables or columns they must be treated in a specific manner usually escaping the words for the RDBMS involved.
Looks like you are using some reserved words for column names: Change and Time
You can escape these with backticks (`), or choose new coumn names
UPDATE `stocks`
SET `price`='$pricez',
`open`='$openz',
`high`='$highz',
`low`='$lowz',
`change`='$changez',
`time`='$times',
`percent`='$percentz'
WHERE symbol = '$symbolz'

PHP array INSERT into MySQL failing [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
Many posts similar to mine,none of them work.
Have an array $data['date'], $data['name'], $data['value'].
Trying to insert into MySQL table MyValues (Date, Name, Value)
Have tried 7-8 different methods, none working.
Would like something like
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO MyValues('Date','Index_Name','Index')
VALUES ($data['date'][$a] ,$data['name'][$a], $data['value'][$a])"
}
Have also tried foreach, building a single string to give to MySQL, etc.
Get this error
Warning: mysql_error() expects parameter 1 to be resource, boolean given on line 45
columnName shouldn't be wrap with single quotes as they are identifiers not string literals.
INSERT INTO `Values` (Date,Index_Name,Index) VALUES (....)
one more thing, the only identifier here that needs to be wrap with backtick is the tableName VALUES because it is a Reserved Keyword.
MySQL Reserved Keywords List
When to use single quotes, double quotes, and backticks in MySQL
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Since Values is a reserved word, you can't use it as is for a table name. You must use backticks to enclose it. Similarly, it is not valid to use single quotes to name columns, you need backticks there too.
Try this:
$out = Array();
$esc = "mysql_real_escape_string";
foreach($data['date'] as $k=>$v) {
$out[] = "('".$esc($data['date'][$k])."', '".$esc($data['name'][$k])."', "
."'".$esc($data['value'][$k])."')";
}
mysql_query("INSERT INTO `Values` (`Date`, `Index_Name`, `Index`) values ".implode(",",$out));
try this, use $a++ not $ee++
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO `Values` (`Date`,`Index_Name`,`Index`)
VALUES ('".$data['date'][$a]."' ,'".$data['name'][$a]."', '".$data['value'][$a]."' ")
}
First, I believe you want your query values quoted, so the result is 'value' and not just value. Example:
mysql_query("INSERT INTO Values(Date,Index_Name,Index) VALUES ('$data['date'][$a]' ,'$data['name'][$a]', '$data['value'][$a]');
If you are doing multiple queries, do something like:
$q = "INSERT INTO Values(Date,Index_Name,Index) VALUES ";
for {
// Add to the string here for each insert item
}
mysql_query($q);
Additionally, please start phasing out PHP's mysql_* library in favor of mysqli or PDO.
First of all, just use PDO/mysqli with prepared statements so you wont ever have any issues like this.
This will solve it though (column names with back-ticks instead of single quotes, and escaped data):
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO `Values` (`Date`,`Index_Name`,`Index`)
VALUES ('".mysql_real_escape_string($data['date'][$a])."' ,
'".mysql_real_escape_string($data['name'][$a])."',
'".mysql_real_escape_string($data['value'])[$a]."'");
}
And try to avoid reserved names for your columns like indexand values.
This works:
for ($a=0;$a<10;$a++) {
mysql_query("INSERT INTO Values('Date','Index_Name','Index')
VALUES ('".$data['date'][$a]."','".$data['name'][$a]."','".$data['value'][$a]."')"
}

more PHP mySQL INSERT fun

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.

PHP escaping question

I have just read the following code but do not understand why there is " and also ' used. Thank you!
$sql='SELECT uid,name FROM users WHERE user="'.mysql_real_escape_string($_POST['login_name']).'" AND ..
There shouldn't be.
The "correct" $sql might look like this:
$sql="SELECT uid,name FROM users WHERE user='".mysql_real_escape_string($_POST['login_name'])."';
You use ' in SQL to say it's a string / literal.
I would suggest that you look into prepared statements, i don't trust mysql_real_escape_string nor mysql_very_real_seriously_this_is_the_real_escape_string, that php-syndrome is not to trust .
This is a PHP program to write an SQL query (and store it in a string).
The target SQL looks like this:
SELECT uid,name FROM users WHERE user="something" AND …
So in PHP terms:
$foo = 'SELECT uid,name FROM users WHERE user="something" AND …'
But you want to replace "something" with dynamic data. In this case the posted login_name — but made safe for MySQL.
$foo = 'SELECT uid,name FROM users WHERE user="' .
mysql_real_escape_string($_POST['login_name']) .
'" AND …'
A better approach is to use prepared statements.
The single quotes surround the SQL-statement ("SELECT..."), the double quote surround the data for the field "user" (though I'd use the quotes the other way around).
The query would look something like this (use single quotes):
SELECT uid FROM users WHERE user='snake'
To assign this query to the variable $sql, you'd have to enclose it in quotes, using double quotes this time, so PHP doesn't assume, the string would end before 'snake':
$sql = "SELECT uid FROM users WHERE user='snake'";
And as you won't always be asking for 'snake' statically, you exchange 'snake' with a dynamic name, exiting/entering the $sql-string by using double quotes again:
$sql = "SELECT uid FROM users WHERE user='" . $dynamic . "'";
If you only wanted one type of quotes, you'd have to escape the quotes that enclose the user-string.
the " will be literally included in the final mysql request so the request send to the mysql database will be:
SELECT uid,name FROM users WHERE user="loginname" AND ..
The single quotes are used to define your string in PHP. The double ones delimit your text field (login_name) in your SQL query.
This is done to avoid escaping the quotes of the query, if the same were used.
You can use single or double quotes for wrapping strings in php. However, there are differences.
With single quote strings, you cannot inline variables (eg: $a = 'hi $name'), nor can you escape characters (eg: $a = 'hi!\n$name').
Here is a nice summary: http://www.jonlee.ca/php-tidbit-single-quotes-vs-double-quotes/
Also on a side note.. Not sure if double quotes should be used for encasing strings in SQL. I do believe you should use single quotes in most DBs.
Looks like the single quotes are used for the PHP code what form the query and the double quotes are use for the query itself
More on Single/Double quotes
you can always echo out the $sql value to see how the Single/Double quotes look before executing the SQL against a DB.
something like:
$sql='SELECT uid,name FROM users WHERE
user="'.mysql_real_escape_string($_POST['login_name']).'";
// Print the SQL
echo $sql."<br />";

Categories