开发者

What do the "\" do in PHP / MySQL scripts

I'm writing a PHP script that performs simple actions to a data base. In order to obtain the MySQL queries I use phpmyadmin to generates the PHP. When I generates using phpmyadmin the commands for example creates a table, this is the result:

$sql = "CREATE TABLE `pyr`.`table1` (`id` INT NOT NULL) ENGINE = MyISAM COMMENT = \'Some comments...\';";

If I insert this on my PHP script, it doesn't work. How开发者_StackOverflowever, if i remove the \, it works. What does the \ do?


It escapes the character ' so it can be written in your string. But you only have to escape the simple quote if your string is enclosed within single quotes. In your example, it's enclosed within double quotes, so you don't have to escape simple quotes! For example :

$a = "I'm a cat"; // no need to escape
$b = 'I\'m a cat'; // you have to escape, otherwise
                   // the second ' would be interpreted as the end of your string!
$c = "He says : \"I'm a cat\""; // You have to escape the double quotes
                                // in this case, because your string is enclosed
                                // within double quotes


Phpmyadmin designed this query to be used with single quotes:

$sql = 'CREATE TABLE `pyr`.`table1` (`id` INT NOT NULL)
ENGINE = MyISAM COMMENT = \'Some comments...\';';

In this case, the backslashes correctly escape the single quotation marks to tell PHP that they aren't the end of the string.


It escapes the quotes in your queries


That is a way to 'escape' quotation marks so you can use the same quotes within a quoted string.

A correct example would be

$somestring="This string has \"quotes\" in it";

But this example is incorrect. There is no need to escape single quotes within that string, because it is double quoted.

See the PHP manual, specifically this part

To specify a literal single quote, escape it with a backslash ()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜