I have a string that looks like this:
"count( IF (my_id = 'mykey',value,100)) mykey"
However, the value 'mykey' that goes right after my_id is in a variable called $which_value;
I fail to see how I can put the $which_value so that it mantains the single quote around it.
Just add the variable inside your string:
"count( IF (my_id = '$which_value',value,100)) mykey"
You should, however, escape the value properly or use prepared statements:
$stmt = $db->prepare("SELECT count(IF (my_id = :my_value, value, 100)) mykey...");
$stmt->execute(array(
':my_value' => $which_value,
));
Or, using plain ol' mysql_ functions:
$sql = sprintf("SELECT count(IF(my_id = '%s', value, 100)) mykey...",
mysql_real_escape_string($which_value)
);
mysql_query($sql);
To include a variable in a string you can do
"count( IF(my_id = '" . $which_value . "',value,100)) mykey"
Its quite hard to make out what exactly you are looking for but this should point you in the right direction (I hope)
You can always use your variable in a double-quoted string like this
"count( IF (my_id = '{$mykey}',value,100)) {$mykey}"
Inside of double quotes variables will be parsed. There is a convenient simple method just using the variable like this:
"count( IF (my_id = '$which_value',value,100)) mykey"
More complex expressions can be wrapped in curly braces like this:
"count( IF (my_id = '{$an_array[3]}',value,100)) mykey"
You may also want to consider escaping the variable string so that it does not break or open up to exploit, the string you are creating. If your id is an integer you can either typecast the variable as an integer:
"count( IF (my_id = '" . (int)$which_value . ',value,100)) mykey"
Or use the sprintf function to insert the variable into the string:
sprintf("count( IF (my_id = '%d',value,100)) mykey", $which_value)
If you need to escape text strings then you'll want to look at escape functions specific to the database you are constructing the query for.
Related
I'm trying to get strings inside a quote.
I'm using regex but i have problems with escaped quotes.
For example, i have this:
$var = "SELECT * FROM TABLE WHERE USERNAME='Carasuman'";
preg_match_all('~([\'"])(.*?)\1~s', $var, $result);
$new = preg_replace('~([\'"])(.*?)\1~s',"<#################>",$var);
The code Works perfect. I got a replaced value in $new and quoted value in $result[1]
$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>";
$result[1] = "Carasuman";
My problem is when i add a scaped quote inside quotes:
$var = "SELECT * FROM TABLE WHERE USERNAME='Carasuman\'s'";
I got this:
$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>'s";
$result[1] = "Carasuman\" //must be "Carasuman\'s";
How I can avoid this error and get $new and $result[1] like first example?:
$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>";
$result[1] = "Carasuman\'s";
Thanks!
for the match, you're never going to get Carasuman's without the \ as a single matched element since you can have match skip over chars within a single match. its either going to grab the Carasuman or Carasuman\'sjust use str_replace to get rid of the backslash
preg_match_all('~([\'"])(.*)\1~s', $var, $result);
$result[2] = str_replace('\\','',$result[2]);
for the replace, the ? in the (.*?) group makes it ungreedy, meaning it will stop at the first match. Remove the ? in (.*?) to make it greedy, meaning it will keep going until the last match
preg_replace('~([\'"])(.*)\1~s',"<#################>",$var);
Edit
Rather than doing the str_replace after the match on $result[2], it would probably be better to just do beforehand on the initial string like:
$var = str_replace("\\'","'",$var);
preg_match_all('~([\'"])(.*)\1~s', $var, $result);
$new = preg_replace('~([\'"])(.*)\1~s',"<#################>",$var);
You still need to make your wildcard match greedy like (.*?) to (.*) in order to have the apostrophe in the name included in the match/replace instead of being counted as the terminating single quote
Why don't you do this:
$var = "SELECT * FROM TABLE WHERE USERNAME='" . mysql_real_escape_string($input) . "'";
I don't think you necessarily need to do regex. Also, mysql_real_escape_string properly escapes your inputs so you can just have $input = 'Carasuman\'s'; or $input = "Carasuman's";
To match quoted strings, you could use the regex '\'.*?(?:\\\\.[^\\\\\']*)*\'' and four double quoted strings '".*?(?:\\\\.[^\\\\"]*)*"'
How do I escape a dot in insert query?
insert into './$x/.' () lues( );
How to escape the dot before $x and after $x, I tried the above but did not work.
Use forward slash, not back slash.
\
also, you need to escape things by placing the escape character BEFORE the thing it's escaping.
E.g.
"INSERT INTO `\$my_table` VALUES(NULL,$asdf,$jkl)"
Ok, but in your case, try this:
insert into `.$x.` () lues( );
Those are not ' but `
That is the backtick character. Same key as ~ on U.S. keyboards.
Concatenating a variable and a string:
$query = 'INSERT INTO `' . $my_table . '` VALUES(NULL,asdf,' . $jkl . ')";
But inside of double quotes "" you can just put the variable names into the string:
$query = 'INSERT INTO `$my_table` VALUES(NULL,asdf,$jkl )";
(Both of the above result in the exact same string being assigned to variable $query)
Take a look at the PHP page on strings
You can see sections on single quote, double quote, and others that will blow your mind (HEREDOC).
I have a string like this:
http://mysite.com/script.php?fruit=apple
And I have an associative array like this:
$fruitArray["apple"] = "green";
$fruitArray ["banana"] = "yellow";
I am trying to use preg_replace on the string, using the key in the array to back reference apple and replace it with green, like this:
$string = preg_replace('|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|', 'http://mysite.com/'.$fruitArray[$1].'/', $string);
The process should return
http://mysite.com/green/
Obviously this isn’t working for me; how can I manipulate $fruitArray[$1] in the preg_replace statement so that the PHP is recognised, back referenced, and replaced with green?
Thanks!
You need to use the /e eval flag, or if you can spare a few lines preg_replace_callback.
$string = preg_replace(
'|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e',
' "http://mysite.com/" . $fruitArray["$1"] ',
$string
);
Notice how the whole URL concatenation expression is enclosed in single quotes. It will be interpreted as PHP expression later, the spaces will vanish and the static URL string will be concatenated with whatever is in the fruitArray.
I have done this many times before, to re-use a value passed into the sprintf() function. But this code is returning a "Warning: sprintf() [function.sprintf]: Too few arguments in..." message.
Here is the code:
$search_clause = sprintf(" (msgBody LIKE %%%1$s%% OR msgSubject LIKE '%%%1$s%%' ) ", mysql_real_escape_string($match1));
Ideally the value of $match1 will be inserted into the segment of the SQL WHERE clause shown above - twice, each wrapped by '%' characters for a wildcard search.
If $match1 = "test", the resulting string value of $search_clause would be:
(msgBody LIKE '%test' OR msgSubject LIKE '%test%' )
What is the obvious mistake I'm making??
The $s is probably getting interpreted as a variable (see variable expansion). Try using single quotes instead:
$search_clause = sprintf(' (msgBody LIKE "%%%1$s%%" OR msgSubject LIKE "%%%1$s%%" ) ', mysql_real_escape_string($match1));
Just escape the $ as \$.
$search_clause = sprintf(" (msgBody LIKE %%%1\$s%% OR msgSubject LIKE '%%%1\$s%%' ) ", mysql_real_escape_string($match1));
^ ^
A problem I recently ran into was that when trying to update a field in my database using this code would not work. I traced it back to having a % sign in the text being updated ($note, then $note_escaped)... Inserting it with sprintf worked fine though.
Should I not be using sprintf for updates, or should it be formed differently?
I did some searching but couldn't come up with anything.
$id = mysql_real_escape_string($id);
$note_escaped = mysql_real_escape_string($note);
$editedby = mysql_real_escape_string($author);
$editdate = mysql_real_escape_string($date);
//insert info from form into database
$query= sprintf("UPDATE notes_$suffix SET note='$note_escaped', editedby='$editedby', editdate='$editdate' WHERE id='$id' LIMIT 1");
You are using sprintf totally wrong. Removing the function call in your code would still do the same thing. It should be:
sprintf("UPDATE notes_%s SET note='%s', editedby='%s', editdate='%s' WHERE id=%d LIMIT 1", $suffix, $note_escaped, $editedby, $editdate, $id);
You should read the manual.
first of all you should be using prepared statements instead of a sprintf-call
but if you absolutely have to do it this way you have to use:
$id = mysql_real_escape_string($id);
$note_escaped = mysql_real_escape_string($note);
$editedby = mysql_real_escape_string($author);
$editdate = mysql_real_escape_string($date);
//insert info from form into database
$query= sprintf("
UPDATE notes_%s /* this is still open for injection, and cannot be properly escaped with mysql_real_escape_string */
SET note='%s',
editedby='%s',
editdate='%s'
WHERE id='%d'
LIMIT 1",
$suffix,
$note_escaped, $editedby, $editdate, $id);
You can escape the % in the source text by replacing it with \% in mysql.
sprintf() is not used much in PHP, unless you need to format data somehow. These two statements work identically in PHP:
$num = 42;
$char = 'q';
$text = sprintf('The number is %d and the character is %s', $num, $char);
$text = "The number is $num and the character is $char";
sprintf's used more in C for "printing" variable data into a string. But PHP can already do that with double-quoted strings, so unless you need to use sprintf's special formatting functions (e.g. %0.2f for a 2-decimal-place float), it's easier to use the regular string method.
From http://php.net/manual/en/function.mysql-real-escape-string.php:
Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.
You need to manually escape the % and _ if any with \% and _. I don't recommend using sprintf, but just improving your escape function.