difference between ' single quote and ` backtick for mysqli_query - php

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

Related

php - single quotes around variables in mysql queries

Why do I see in several examples of mysql queries via php the syntax:
$q = "CREATE TABLE '$tablename' ('$t_id_name')";
or things similar to that? I'm asking about the single quotes around the variable names. Is this required in MySQL strings? If I echo the string, it seems to expand the variables whether the quotes are there or not.
And would this pose a problem if this were done for something that was intended to be an integer?
To answer your question, the quotes are necessary, but not to expand the variable. A typical SQL query would look like this:
$q = "SELECT * FROM `table` WHERE `first_name` = 'user3475234'";
Now, consider the following example:
<?php
$tablename = "users";
$user = "user3475234";
$q = "SELECT * FROM `$tablename` WHERE `first_name` = '$user'";
echo $q;
This will display: SELECT * FROM `users` WHERE `first_name` = 'user3475234'. Note that the quotes weren't necessary to output the string, but they were a necessary part of the query.
That being said, code like this opens your script to SQL injection. I won't explain too much about it, since there are plenty of resources discussing it, but consider the example where someone's username is user3475234' OR 1==1--. This username will effectively return all users in the table.
You must use backticks (`) for field or table name especially if the field or table name are same with mysql command. And you need to use single-quote (') for value.

Syntax Help for Query

I'm trying to query my MySQL database to get information about a user. You submit a form on a previous page and then you go into the page and connect to the database and all that good stuff. I just have a quick question on syntax for the SELECT function for a query. I'm trying to say "select from tbl_name where the field first name concatenated with the field last name (with a space in between) equals the variable $user.
I figured with PHP I need to put slashes in front of the quotation marks. It doesn't seem to return any value though. Am I just using incorrect syntax?
$user=$mysqli->real_escape_string($_POST['user']);
$sql="SELECT * FROM tbl_name WHERE firstname.\" \".lastname='$user'";
You will have to use SQL's CONCAT() in your WHERE clause to join the firstname and lastname columns together:
SELECT
*
FROM
tbl_name
WHERE
CONCAT(firstname. ' ', lastname) = ?
Using your existing code in PHP (for copy+paste):
$sql = "SELECT * FROM tbl_name WHERE CONCAT(firstname, ' ', lastname) = '" . $user . "'";
* Also worth noting: since you're using MySQL you can legally-use single-quotes and/or double-quotes for strings in your queries (T-SQL is bound to single quotes for strings). Because of this, if you're wrapping your whole query with double-quotes in PHP you can use single-quotes inside your SQL-query instead of having to escape your double-quotes. This is more of a programmer's-preference tip, but one that may save you a quote-escaping headache one day =P
i think it is this what you are looking for??
$sql = 'SELECT * FROM '.$tbl_name .' WHERE CONCAT(firstname," ",lastname )='.$user.' ';

Why won't my SQL work?

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.

SQL and PHP problems

What is wrong with this query?
$query3 = "INSERT INTO Users
('Token','Long','Lat')
VALUES
('".$token."','".$lon1."','".$lat."')";
You have several issues with this.
Column names should be backtick escaped, not quoted (also LONG is a datatype in MySQL hence it's reserved and must be backtick-escaped).
You have SQL injection problems if those arguments aren't escaped.
You should provide us with the result of mysql_error() if it's not working.
Try running this code:
$token = mysql_real_escape_string($token);
$lon1 = mysql_real_escape_string($lon1);
$lat = mysql_real_escape_string($lat);
$query3 = "INSERT INTO `Users` (`Token`, `Long`, `Lat`)
VALUES ('{$token}', '{$lon1}', '{$lat}')";
$result3 = mysql_query($query3) or die("Query Error: " . mysql_error());
If that still doesn't work, give us the error message that's produced.
Long is the mysql reserved word and reserved words needs to be enclosed in backticks
$query3 = "INSERT INTO Users
(`Token`,`Long`,`Lat`)
VALUES
('".$token."','".$lon1."','".$lat."')";
You're using single quotes around your field names. This isn't valid in any SQL variant I know of. Either get rid of them or quote the field names in the correct way for your SQL flavor.
Your code likely has an SQL injection vulnerability, unless you left out the code that escapes $token etc
You shouldn't be putting values into the SQL string like that. This isn't the 1990s - we have parametrized queries now.
The mysql_ functions make it a bit difficult to do queries properly. Switch to either mysqli or PDO.

PHP syntax for postgresql Mixed-case table names

I have a code below:
<?php
require "institution.php"
/* in this portion, query for database connection is executed, and */
$institution= $_POST['institutionname'];
$sCampID = 'SELECT ins_id FROM institution where ins_name= '$institution' ';
$qcampID = pg_query($sCampID) or die("Error in query: $query." . pg_last_error($connection));
/* this portion outputs the ins_id */
?>
My database before has no mixed-case table names, that's why when I run this query, it shows no error at all. But because I've changed my database for some reasons, and it contains now mixed-case table names, i have to change the code above into this one:
$sCampID = 'SELECT ins_id FROM "Institution" where ins_name= '$institution' ';
where the Institution has to be double quoted. The query returned parse error.
When i removed this portion: where ins_name= '$institution', no error occured.
My question is how do I solve this problem where the table name which contains a mixed-case letter and a value stored in a variable ($institution in this case) will be combined in a single select statement?
Your answers and suggestions will be very much appreciated.
You can use the double quote instead
$sCampID = "SELECT ins_id FROM \"Institution\" where ins_name= '$institution'";
<?php
require "institution.php"
/* in this portion, query for database connection is executed, and */
$institution= pg_escape_string($_POST['institutionname']);
$sQuery = "SELECT ins_id FROM \"Institution\" where ins_name= '$institution'";
$qcampID = pg_query($sQuery)
or trigger_error("Error in query: $sQuery." . pg_last_error($connection));
/* this portion outputs the ins_id */
?>
Note
pg_escape_string as it ought to be used, not to protect from any injections but as just a part of the syntax.
trigger_error which should be used instead of echo (and note proper variable name)
and double quotes or your variable won't be extrapolated ( http://php.net/types.string for ref)
and slashes at double quotes (same ref)
$sCampID = 'SELECT ins_id FROM "Institution" where ins_name= \''.$institution.'\'';
String escaping.
As another commenter posted, read about SQL injection. What I have is not injection safe, consider using something with prepared statements, preferably PDO.
To add to other answers (quote the table name, and use prepared statements to gain security and performance), read about PG and tables case sensitivity. If you have the option, you might consider to change your db schema, so that tables names (and columns and identifiers in general) are all lowercase. That would simplify a little your queries - (but require you to check all your actual quoted queries and unquote them).
What happens if $institution contains the following string: ' or 1 = 1; --
That's what we call an SQL injection attack, and it's a super-easy way for hackers to steal your data -- and get you into big trouble with your customers.
You need to escape that string using pg_escape_string() before putting it into an SQL query. I like to use sprintf() to build my queries:
$sql = sprintf("SELECT ins_id FROM \"Institution\" where ins_name= '%s'", pg_escape_string($conn, $institution));
In the above example, $conn is the connection identifier, created by calling pg_connect().

Categories