What does '\" actually mean in PHP Syntax? - php

I have a piece of code and i keep getting syntax errors for codes like thess :
$query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";
Now when i reformat it as :
$query ="SELECT * from `jos_menu` where `id` = ".$parent;
That is when i remove : '\"
it works fine. So i am just wondering, what does ('\") actually do ???

\ is the escape character. It means the next character should be taken literally, without care for its special meaning.
In PHP, you would generally see '\" inside of a string if the string were delimited with double quotes (and the developer just wanted a preceding single quote).

It works fine because you have a numeric value - so mysql automatically converts a string to a number for you. So you get 2 different queries (assuming that $parent = 42;:
SELECT * from `jos_menu` where `id` = 42
vs
SELECT * from `jos_menu` where `id` = "42"

It denotes escaped characters. The next character that appear after it, will be taken as its current form.
Your Query is incorrectly escaped
$query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";
//^ You mismatched the quotes from here
A correctly escaped query should be
$query ="SELECT * from `jos_menu` where `id` = \"$parent\"";
// ^ Note here " will printed as it is within the query
For example,
If $parent was 2, then the query would be
SELECT * from `jos_menu` where `id` = "2"

The only problem with
$query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";
Is that you missed a few ':
$query ="SELECT * from `jos_menu` where `id` = ".'\"'.$parent.'\"';
In PHP, a string can either be:
$var = 'This is a string';
Or
$var = "This is a string";
If you want to put " inside a string that you already started with ", you need tell PHP that you don't want your second " to end the string but use the character " as part of the string itself. This is what \" does. It tells PHP that Don't give the " character any special meaning; since normally if you started the string with ", the next " would end the string.
\ means remove any "special" meaning to the next character
This only works if the character after the \ would have had special meaning. Some examples:
Suppose we want to print Hello "World". I am a string!:
$var = "Hello "World". I am a string!";
In this example we will have errors. Since we started the string with ", the next " will close the string. So what PHP thinks:
" Start of string
Hello part of string variable.
" Hey, since I saw that the string was started with ", this must mean the end of it!
World" <-- Error
Stop processing and throw errors.
However, if we write:
$var = "Hello \"World\". I am a string!";
Now, PHP thinks:
" Start of string
Hello part of string variable
\ Ah, okay, the next character I should remove any special meaning
" Okay, this is immediately after \, so I just use it normally, as a ".
World part of string
\ Okay, the next character I will remove any special meaning
" This is now a normal "
. I am a string! - part of string variable.
" Ah! Since the string was started with ", this must be the ending.
; ends statement.
Hopefully this clarifies things for you.

A few things:
To denote the next character a literal, '\'' // outputs a single '
Special characters, \n newline, \t tab character etc

The back-slash escapes next charactor after it; in your example this would work:
$query = "SELECT * from jos_menu where id = ".$parent;
But so would this:
$query = "SELECT * from jos_menu where id = $parent";
When escaping quotations, it varies on the type of parenthesis used. With double parenthesis, you can include the variable right into the string, just be careful of accessing arrays by key:
$var = "This \"works\" ".$fine.".";
$var = "This 'also' works just $fine.";
$var = "This $will['fail'].";
$var = "However, $this[will] work and so ".$will['this'].".";
Same rules apply for single parenthesis.

Related

Checking function with spaces in it in php

I am using this query
"SELECT * FROM items WHERE itemname LIKE '%$name%'"
If $name="alex", then the query returns the correct information. But if $name="alex " with trailing whitespace, then no results are returned.
If $name="alex dude", then this is valid, but $name="alex dude " is not. I only want to remove whitespace at the end of the string.
I have written a function to clear out spaces at the end of name. This is the function.
function checkname($dataname)
{
$func_name ="";
$checker = substr($dataname, -1);
if($checker == " ")
{
$func_name = substr_replace($dataname, "", -1)
function checkname($dataname);
}
else
{
$dataname = $func_name;
}
return $dataname;
}
This gives me a PHP Parse error:
syntax error, unexpected 'function' (T_FUNCTION) in C:\inetpub\vhosts\httpdocs\compare.php on line 176`.
I don't understand why recursively calling a function is giving me an error.
Can you guys help out with this? Is there a better solution or better SQL query than I am using?
There are two reasons you'll get errors. The first reason, and the reason you're seeing the message:
Parse error: syntax error, unexpected 'function'
is that you're missing a semicolon after $func_name = substr_replace($dataname, "", -1).
function is unexpected because you haven't terminated the previous line.
If you fix that, you'll still get an error, because you're using function checkname($dataname); to do the recursive call, when it should be return checkname($dataname); If you use it the way you have it, you'll get a cannot redeclare function error.
If you want it to work recursively, it can be simplified to
function checkname($dataname) {
if (substr($dataname, -1) == " ") {
return checkname(substr_replace($dataname, "", -1));
}
return $dataname;
}
But as others have said, this does basically the same thing as trim() or rtrim().
You can do direcly in sql
"SELECT * FROM items WHERE itemname LIKE concat('%', trim('$name'), '%')"
or rtrim
"SELECT * FROM items WHERE itemname LIKE concat('%', rtrim('$name'), '%')"
You can use trim, it's PHP native function stripping whitespace from the beginning and end of a string.
$trimmed = trim(' my string ');
echo $trimmed; // 'my string'
You can find more informations regarding it in the documentation.
By default, it will remove ordinary space, tab, new line, carriage return, NUL-byte and vertical tabs.
You can also control which characters are removed at the start and end of the string by using a second parameter to the trim function as specified in the documentation.
Try
SELECT * FROM items WHERE itemname LIKE '%". trim($dataname) ."%'"
trim($string) Strip whitespace (or other characters) from the beginning and end of a string
I'm using str_replace function
$name="a l e x" ;
$abcd = str_replace (" ", "", $name);
$res=mysql_query("SELECT * FROM `name` WHERE `name` LIKE '%$abcd%'") or die(mysql_error());
while($x=mysql_fetch_array($res))
{
echo $x['name']."<br>";
}
str_replace (" ", "", $name) helps to your problem
or by using sql
"SELECT * FROM `name` WHERE `name` LIKE '%".str_replace (" ", "", $name)."%'"
and it removes all your white spaces.

single quote within double quote

i read string documentation on PHP and found out that Single quoted strings will display things almost completely "as it is." Variables and most escape sequences will not be interpreted except \' and \\
I wanted to display a hyperlink whose address should be http://localhost/kk/insert.php/?id="4"
i tried the following code
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=".$id."'>edit</a>";
But it's displaying http://localhost/kk/insert.php/?id=4 (there are no double quotes surrounding 4)
However, i accomplished the result by using
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
My question is that single quotes does interpret \" escape character. So why the first code is not displaying double quotes (that are placed inside single quotes). What am i missing?
You shouldn't have quotes around the integer. Your url should be
http://localhost/kk/insert.php/?id=4
which is accomplished using the following code:
$id = 4;
echo 'edit';
You're dealing with TWO languages there. PHP is doing the echo, and the " quotes are parsed/removed by PHP. Then there's the ' quotes, which are used in the HTML to delimit the href attribute.
With your escaped second version:
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
^--php ^--html ^^--escaped for PHP
Normally that " before $display_result would TERMINATE the PHP string you've been echoing. But since it's been escaped (\"), the escape tells PHP to treat that quote as plaintext, and NOT as a quote. So the PHP string continues, and when this code actually executes and is output from your server, the browser will actually see:
<a href='http://localhost/kk/insert.php/?id="XXX"'>edit</a>
The interpretting difference between single quote and double quote you found is this:
$a = 4;
echo '$a' . "$a"; // $a4
// '$a' just prints `$a`
// "$a" prints `4`, it's interpretted
// alternatively "\$a" prints `$a`
As for the escaping. If your string delimiter is a single quote then you don't need to escape double quotes, and vice versa.
$a = "don't";
// vs
$a = 'don\'t';
$a = '"quote"';
// vs
$a = "\"quote\"";
To do it with your first example, just do :
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=\"".$id."\"'>edit</a>";

Get and replace quoted strings with regex

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 '".*?(?:\\\\.[^\\\\"]*)*"'

Regexp and variable

I have this form, wich outputs some letters and a wordlength. But I've got some problems with getting a right output from my database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$letters = mysql_real_escape_string($_POST['letters']);
$length = mysql_real_escape_string($_POST['length']);
echo "Letters: $letters";
echo "Lengte: $length";
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[$letters]{$length}' ")
or die ('Error: '.mysql_error ());
while ($row=mysql_fetch_array($res)){
echo $row['word'];
echo "<br />";
}
}
else {
echo "Foutje";
}
If I change $length to the integer that was inputted by the form my script works. Copy/pasting [$letters] 6 times works also. I guess there is a problem with quotes but I totaly can't figure out what it exactly is.
Can anyone see what I did wrong?
Thanks.
The {} are being interpreted by PHP as delimiters for the variable inside since you are using a double-quoted string. Change your quoting around with concatenation:
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[" . $letters . "]{" . $length ."}'")
Or double up the {} inside a double-quoted string so the outer pair are interpreted as literals.
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[$letters]{{$length}}' ")
Note, you should also verify that $length contains a positive integer.
if (!ctype_digit($length)) {
// error - length must be an int
}
try doing this:
res=mysql_query("SELECT word FROM words WHERE word REGEXP '[".$letters."]{".$length."}' ")
I have a hunch that the $ is getting intepreted as part of the regex

Escape a dot in mysql insert query

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

Categories