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 />";
Related
'...where T4."firstName"!=\'ERD\''
*I am sure you know but: ''\'ERD\'' means "ERD" inside single quotation marks.
This is a part of sql query but I want to use a variable instead of ERD. Having trouble with double and single quotation marks. How should I write the variable?
An option to prevent SQL injection is appreciated. I am using ODBC.
I would suggest concatenating it:
"SELECT * from table1 where firstName = '" . $ERD . "'";
I need to find all instances in a database where there is a ' in the name.. Like Jason's Store.
Problem is, the ' messes the query up
SELECT *
FROM `paydayloan`
WHERE `company` LIKE '%'%'
The ' in the middle ends the string, How do I get around this?
You can simply use double quotes:
SELECT * FROM paydayloan WHERE company LIKE "%'%";
Using MySQLi or PDO prepared statements, this wouldn't be an issue.
Otherwise you need to escape your values.
You could escape the quote like this:
SELECT * FROM paydayloan WHERE company LIKE '%''%'
You should use double quotes.
SELECT * FROM paydayloan WHERE company LIKE "%'%";
when I write a query for MySQL, usually use a form like this:
$column= "column_name";
$query = "SELECT * FROM table_name WHERE \"".$column."\"" = \"some_value\" ";
if I want to avoid using the \"". sequence for the variables, can I use this other form or there could be some compatibility issues or some other problem ?
$column= "column_name";
$query = "SELECT * FROM table_name WHERE \"$column\" = \"some_value\";
In both of these cases what you're doing is fine, but a few notes:
1) What you're doing in your first form is using the strings like string literals, which means you can/should use single quotation marks instead of double quotation marks, as they are parsed much faster.
$column = 'column_name';
$query = 'SELECT * FROM table_name WHERE ' . $column . ' = "some_value"';
What you're doing in the second example is also fine, it just depends on the reason you're trying to avoid using the escape character, but if you're just doing it for the sake of readability, what you have is fine.
Worth noting is that handling queries the way you're doing here is getting deprecated and you should take a look at PDO and inject your values that way.
Edit Per Comments Above - Removed " from around the column.
Yes, you can.
Strings delimited with double quotes are interpreted by the PHP parser.
to make sure, the variable is identified correctly, put it into curly brackets
Example
$variable = 1;
$array = array( 1,2 );
$object = new stdclass();
$object->member = 1;
$string = "You can basically put every kind of PHP variable into the string. This can be a simple variable {$variable}, an array {$array[0]} or an object member {$object->member} even object methods.";
If you want PHP to take the $variable literally without interpretation, put the string into single quotes.
Another method I really like to use for queries is the heredoc notation
$sqlQuery = <<< EOQ
SELECT
"field"
FROM
"table"
WHERE
"id" = '{$escapedValue}'
EOQ;
One more note:
In SQL you should delimit values with the single quote, and identifiers like table name and field names with double quotes (ANSI compatible) or the back tick ```
I'm seeing some weirdness when I try to run a query using PDO. The following code shouldn't return results, but it does:
$safe_path = $this->_databaseConnection->quote($unsafe_path);
$sql = "SELECT * FROM routes WHERE path=$safe_path LIMIT 1";
$statement_handle = $this->_databaseConnection->query($sql);
var_dump($statement_handle->fetchAll());
I'm confused because there aren't single quotes around the $safe_path variable as there would be if I were using the mysqli extension - but it's working. If I enclose $safe_path in quotes, no results are returned. This seems strange to me.
You are already quoting the $safe_path variable with your first line in the sample:
$safe_path = $this->_databaseConnection->quote($unsafe_path);
That is why it works as it stands. If you attempt to add quotes yourself in the:
$sql = "SELECT * FROM routes WHERE path='$safe_path' LIMIT 1";
line then you would be doubling up the quotes and therefore breaking the SQL query.
Please see the manual page for quote() for more information:
PDO::quote() places quotes around the input string (if required) and
escapes special characters within the input string, using a quoting
style appropriate to the underlying driver.
The PDO quote method just add quotes in a string context.
http://php.net/manual/en/pdo.quote.php
PDO::quote() places quotes around the input string (if required)[...]
Aren't you adding quotes?
$safe_path = $this->_databaseConnection->quote($unsafe_path);
I have a searchable database of the House and Senate and I just want to make a simple web page that can search this database. The only problem is, while I'm comfortable writing SQL select statements, how do I properly format them for use in PHP?
For example, here's my radio button to select Senators by state:
$sql = "";
if ($_POST['pkChamber'] == "Senate") {
if ($_POST['pkParty'] == "Y") {
$sql = SELECT * FROM senateinfo
WHERE state = (Variable = "stname")
ORDER BY last_name, first_name');
}
else
{
$sql = SELECT * FROM senateinfo
WHERE state = (Variable = "stname")
ORDER BY last_name, first_name
}
}
I am not sure what you're asking for, But I have a good example of reliable and safe way for building WHERE statement dynamically:
$w = array();
$where = '';
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where = "WHERE ".implode(' AND ',$w);
$query = "select * from table $where";
Hope this helps.
Your query seems fine. I think you just need to understand some of the finer points of string parsing in PHP.
When you use double quotations (") to enclose a string, PHP actually will try to parse it looking for variables and/or other php code to process first. Something like this:
$sql = "SELECT * FROM table WHERE state = '{$state}' AND user = {$user->id}";
PHP will substitute out $state for whatever is defined in that variable and the same for the id of whatever user is instantiated in that class. (Also, you don't have to wrap your simple variables in {}. It does help with readability but is only required for class methods/variables.)
If you use single quotes (') to enclose a string, PHP simply treats it like normal. For your above query, I would suggest enclosing it in single quotes like this:
$sql = 'SELECT * FROM senateinfo WHERE state = (Variable = "stname") ORDER BY last_name, first_name)';
If you want to use variables later on in this query, then you will need to escape the double quotations that are in there like this:
$sql = "SELECT * FROM senateinfo WHERE state = (Variable = \"stname\") ORDER BY last_name, first_name)";
This way, PHP doesn't error out thinking you were trying to concatenate strings incorrectly when all you were doing was pasting a query.
You need to focus on one issue at a time.
Try to avoid writing SQL in PHP until you've a clear handle on strings in PHP, and how to inject variables into those strings. So:
Read up on string quoting in PHP (double quotes vs. Single quotes, and yes, HEREDOC)
Read up on variables in strings in PHP (note that if it doesn't have a $ dollar sign, it's a CONSTANT, not a string variable. Start off right with $strings and $variables where they're supposed to be used, not CONSTANTs, which only fall back to turn into strings if nothing else is available.)
Read up on binding SQL in PHP. Anything else will lead you down the path of SQL injection. If there are only naked strings used in your PHP SQL, then you are setting yourself up for failure when you finally deploy your web scripts to the harsh and unforgiving Internet. It's full of sharks ready to take advantage of SQL injection prone scripts.
Here is an example of code I use daily to bind SQL, centered around a custom function that makes it easy:
query("select * where someTable where someTable_id = :bound_id", array(':bound_id'=>13));
I can get you a function for creating bound SQL simply like that later (when I'm actually at a computer instead of mobile) if you're interested.
I use HEREDOCs for writing out non-trivial queries:
$sql = <<<EOL
SELECT blah, blah, blah
FROM table
WHERE (somefield = {$escaped_value}) ...
ORDER BY ...
HAVING ...
EOL;
Heredocs function as if you'd done a regular double-quoted string, but with the bonus of not having escape internal quotes. Variable interpolation works as expected, and you can do indentation on the text as well, so your query looks nicely formatted
I always do mine like this to keep it looking nice.
$sql = "SELECT * FROM senateinfo " .
"WHERE state = (Variable = "stname") " .
"ORDER BY last_name, first_name')";