How to use PDO::quote without getting string surrounded by quotes? - php

I try to use PDO::quote to escape a string in a LIKE expression, so the user string must not be surrounded like in :
LIKE "%userStringToEscape%"
Is there a way to do that ?

$var = "%userStringToEscape%";
$var = $stmt->quote($var);
$sql = "SELECT * FROM table WHERE field LIKE $var";
same goes for the prepared statements

Use substr($db->quote($var), 1, -1)
Really though, don't. You'll end up with larger problems than the ones you started with.
The clean solution to do this is, of course, $db->quote('%'.$var.'%')

Just do:
$like = $pdo->quote("%{$userStringToEscape}%");
$sql = "SELECT * FROM field LIKE {$like}";
http://php.net/manual/en/pdo.quote.php

Related

php variable is treated like string

I have this issue.
I need to receive, from comments column in mysql database, a string like this:
WHERE IDTable=$number
When i get this comment i have to put it like a Where clause in my query.
But if i write this code
$where=getComment($table,$field); //I get the string i wrote above
$number=5; //I initialize $number in my code
$sql="SELECT * FROM table $where";
print "SQL: $sql";
i get this:
SELECT * FROM table WHERE IDTable=$number
obviously i'd like to have in response:
SELECT * FROM table WHERE IDTable=5
How can I do that?
Thanks
I strongly suspect that the code you have a problem with is not the same code as above, as the above would not produce the result you stated. At the very least you are missing the definition of the function you're calling, to create said output.
However, what would produce such a result is by using single quotes around a string. Which prevents variable expansion, and treats them as regular strings instead.
Not only that, but your code is out of order as well. You cannot use a variable before you have declared it, as it simply does not exist yet.
The string returned by getComment() will not be parsed, so any PHP variables in it ($number) will be returned as the literal string.
I can think of two options -
1
Allow an extra parameter for getComment() so you can pass it $number
$number=5;
$where = getComment($table,$field,$number); // returns "WHERE IDTable=5"
$sql="SELECT * FROM table $where";
2
Do not return $number from getComment(), then you can add it when you build the query.
$where=getComment($table,$field); // returns "WHERE IDTable="
$number=5;
$sql="SELECT * FROM table $where $number";
Perhaps the String Value you got from MySQL: WHERE IDTable=$number may have been enclosed within Single Quotes. Consider the Example Below.
$number = 22;
$str = 'WHERE IDTable=$number';
var_dump($str); //<== YIELDS:: 'WHERE IDTable=$number' B'COS IT'S IN SINGLE QUOTES
$parts = explode("=", $str);
list($where, $var) = $parts;
$var = ltrim(trim($var), "\$");
$newStr = trim($where . "=" . $$var);
var_dump($$var); //<== YIELDS:: int 22
var_dump($newStr); //<== YIELDS:: 'WHERE IDTable=22' (length=16)
Assuming this is the case with your String; to get around that, You may simply want to extract the Variable from the String and then rebuild the String as the Snippet above demonstrates. Otherwise; if you have a possibility of enclosing the String in Double Quotes, this convoluted work-around would be utterly irrelevant.

Zend 2 - DB - Escape value without quoting it

I'm looking for a clean way to escape value for SQL query without quoting it.
Let's say i have a value It's cool. Now I would like to simply get escaped string It\'s cool, just like when using for example mysqli_real_escape_string() function for mysqli driver.
The problem is that all Zend\Db\Adapter\Platform interface's quoting methods adds single quotes to the value which means I get 'It\s cool'.
Simplest way I found to do this is to trim quotes after usage of quoteValue() method.
$raw = "It's cool";
$quoted = $this->db->platform->quoteValue($raw);
$final = trim($quoted, "'");
But it's of course a dirty solution and I don't want it to be like this in every place I need escaped-only value.
Is there any clean way to do this simple thing in Zend2?
Maybe you can try something like this:
$sql = "UPDATE posts set comment = :value where id = :id";
$data = ['value' => "It's cool", 'id' => 123];
$stmt= $this->tableGateway->getAdapter()->createStatement($sql);
$stmt->prepare($sql);
$stmt->execute($data);

How to escape # in PHP

How can I escape the # in PHP? When I use it in a query it turns the remaining line of code into a comment. This is what I have right now:
$columns = "head1, #_search, #_stuff";
$result = mysql_query("SELECT $columns from table LIMIT $k,$j");
I can't just put escape # right after $columns since it will just become a comment.
~edit: yes I probably should have copied the code directly, but some of it is confidential and much more complicated.
You should be using quotes for your strings:
$columns = 'head1, #_search, #_stuff';
However, this still doesn't make much sense.
It's also recommended to favour PDO or mysqli over mysql_*
Try adding backslashes
$columns = 'head1, \#_search, \#_stuff';
How about the following ? :
$columns = "head1, `#_search`, `#_stuff`";
You can use `(backtick) to quote reserved words.
If you want to quote table/column name you can do the following example:
SELECT * FROM `#table1` WHERE `#table1`.`#column1` = 1;
Reference
Shouldn't it be a string literal?
$columns = 'head1, #_search, #_stuff'

Using PHP variable inside a query

I am using a query inside PHP as:
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,1';
Where I am trying to insert a PHP variable instead of 1 in the limit..
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,"'.$_GET['limit'].'"';
but it shows me an error. There are some errors in keeping $_GET['limit'].
Three things:
The way you're writing out those queries is a bit hard to read. Personally I prefer using a multi-line heredoc syntax (as per below), but this isn't strictly required;
Any user input should go through mysql_real_escape_string() to avoid SQL injection attacks. Note: "user input" includes anything that comes from the client including cookies, form fields (normal or hidden), query strings, etc.; and
You don't need to quote the second argument to LIMIT clause, which is probably the source of your problem, meaning put LIMIT 0,5 not LIMIT 0,"5".
So try:
$title = mysql_real_escape_string($_GET['title']);
$author = mysql_real_escape_string($_GET['author']);
$limit = (int)$_GET['limit'];
$query = <<<END
SELECT *
FROM #__chronoforms_UploadAuthor
WHERE text_6 LIKE "$title%"
AND text_7 LIKE "%$author%"
LIMIT 0,$limit
END;
Also, one commentor noted that % and _ should be escaped. That may or may not be true. Many applications allow the user to enter wildcards. If that's the case then you shouldn't escape them. If you must escape them then process them:
$title = like_escape($limit);
function like_escape($str) {
return preg_replace('!(?|\\)((?:\\)*)([%_])!', '$1\$2', $str);
}
That somewhat complicated regular expression is trying to stop someone putting in '\%' and getting '\%', which then escape the backslash but not the '%'.
The hash sign (#) starts a comment in SQL, which looks like your problem
Want bunch of awful answers!
a. To solve the limit problem:
$limit = intval($_GET['limit']);
and then
...LIMIT 0, $limit
in the query.
b. To sanitize $_GET['title'], as many mentioned:
$title = mysql_real_escape_string($_GET['title']);
So the final code must be
$limit=intval($_GET['limit']);
$title = mysql_real_escape_string($_GET['title']);
$author = mysql_real_escape_string($_GET['author']);
$query = "SELECT * from #__chronoforms_UploadAuthor
WHERE text_6 like '$title' and text_7 like '%$author%'
LIMIT 0, $limit";
You've enclosed the $_GET['limit'] in double-quotes, which is the source of the problem.
Try this:
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,'.$_GET['limit'];
Also as Cletus mentions in this answer, there are many, more serious problems you need to resolve.
Remove the double-quotes around $_GET['limit']. The two numbers that the LIMIT clause takes should not be quoted.
This should work:
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,'.$_GET['limit'];
But you really should filter incoming data...
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.mysql_real_escape_string($_GET['title']).'%" and text_7 like "%'.mysql_real_escape_string($_GET['author']).'%" limit 0,"'.intval($_GET['limit']).'"';

MySQL Query in CodeIgniter with Session ID

Let's say I have a query:
" SELECT * FROM table
WHERE donor_id = " .$this->session->userdata('id') ."
GROUP BY rating"
However, it appears that I get a mysql syntax error here, citing that $this->session->userdata('id') gives me '25' for example, instead of 25. Are there any workarounds here to prevent $this->session->userdata('id') from being quoted?
Thanks.
In CI, I do this all the time:
$id = intval($this->session->userdata('id'));
$sql = " SELECT * ".
" FROM table ".
" WHERE donor_id = {$id} ".
"GROUP BY rating ";
//process $sql below
Creating query like this will make you easier to spot bug and prevent SQL injection. Use concatenation when you need to split query to multiple lines instead of make it a long multiple string is to prevent the actual query string got too long. Indent the SQL keyword is to make it easier spot logical and syntax bug.
intval($this->session->userdata('id'))
Assuming you mean that it is returning you a string instead of an integer you could always try using settype or intval:
$var = '2';
settype($var, "integer");
$var = intval($var);
However, if you mean that the quotes are for some reason hard-coded in, you could do a string replace, if you are sure that the value will not contain quotes:
ech str_replace("'", "", "'2'"); // prints 2

Categories