PDO: Quotes in SQL - php

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);

Related

SQL query statement in PHP doesn't work

I hava a problem using SQL query in PHP, I've tried to find out what wrong about my code, anyway this code work well in SQL query via phpMyAdmin and show the result correctly
When I use the condition WHERE RoomNo ='D003' or any Room No. (I tried both 'D003' and "D003") it doesn't query anything at all
Please help.
Here is my code
onclick = "javascript: openListOfValue('ADD_LINE','Room','Select RoomNo, RoomType FROM Room WHERE RoomNo ="D003"','RoomNo,RoomType');
<script>
function openListOfValue(mode, table, initSQL, columnname){
window.open("listofvalue.php?mode="+mode+"&table="+table+"&initSQL="+initSQL+"&columnname="+columnname,"popup","width=600,height=350");
}
</script>
SQL string literals are quoted with single quotes.
As your HTML string literal uses double quotes, you are using single quotes for your Javascript string literal. In order to have single quotes inside this string you must escape them. In Javascript you use the backslash to escape a single quote:
onclick = "javascript: openListOfValue('ADD_LINE','Room',
'Select RoomNo, RoomType FROM Room WHERE RoomNo = \'D003\'','RoomNo,RoomType');"

MySQL Escaping Single Quotes With mysqli_real_escape_string

When I am inserting into a database with mysqli_real_escape_string, I am finding that my single quotes are been escaped with \\ rather than \ which is causing my query to fail. See below:
NOTE: $link is my db connection var.
$string = mysqli_real_escape_string($link, "BEGIN testing quotes - don't use quotes END");
$query = "INSERT INTO table (field) VALUES ('".$string."')";
When I echo out my query, I get:
INSERT INTO table (field) VALUES ('BEGIN testing quotes - don\\'t use quotes END')
which is causing a SQL syntax error. I cannot seem to find a setting anywhere that can change this. If I copy the echo'd query into MySQL workbench and remove a \, the query insert's perfectly.
I have had a look through Stack Overflow and cannot find anything relating to this, and also searched through Google with no luck.
I have many queries that need escaping across my entire website. Could a setting be set to automatically apply escaping of strings pre-insert without having to go through and update all my variables? If not, Is there anyway I can alter the mysqli_real_escape_string function without having to manually check every string I insert for single quotes etc?
I appreciate any assistance with this.
As Krishna Gupta suggested, stripslashes resolved my issue:
$string = mysqli_real_escape_string($link, stripslashes("BEGIN testing quotes - don't use quotes END"));
Thanks.

Can I use a variable directly inside the echo function without cause any incompatibility?

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 ```

MySQL_real_escape_string not adding slashes?

So I do this:
<?php
session_start();
include("../loginconnect.php");
mysql_real_escape_string($_POST[int]);
$int = nl2br($_POST[int]);
$query = "UPDATE `DB`.`TABLE` SET `interests`='$int' WHERE `user`='$_SESSION[user]'";
mysql_query($query) or die(mysql_error());
mysql_close($con);
?>
And let's say that $_POST[int] is "Foo' bar." The single-quote remains unescaped AND I get a MySQL error when running the script, due to the quote. What's wrong?
m_r_e_s() RETURNS the escaped value, it doesn't modify the original.
$int = mysql_real_escape_string($_POST['int']);
$query = "UPDATE ... interests = '$int' ...";
Note that I've added quotes around the int in the POST value. Without the quotes, PHP sees it as a constant value (e.g. define()). If it doesn't find a constant of that name, it politely assumes you meant it to be used a string and adjust accordingly, but issues a warning. If you had done
define('int', 'some totally wonky value');
previously, then you'd be accessing the wrong POST value, because PHP would see it as $_POST[some totally wonky value] instead.
You're not using the results of mysql_real_escape_string in your query.
Try doing this:
$int = nl2br(mysql_real_escape_string($_POST[int]););
You should be using prepared statements. It has a slight learning curve over mysql_* functions, but is well worth it in the long run.
You should quote your strings, like $_POST['int'] instead of $_POST[int].
At the top of your file put error_reporting(-1);

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