0

Why do I get this error even when I am using mysqli_real_escape_string? In this example, doesn't mysqli_real_escape_string escape quotes in the string?

Parse error: syntax error, unexpected 'X' (T_STRING) in C:\xampp\htdocs\PHP\processor.php on line 20

<?php
    $text = "I'm "X-MAN"";

    $con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "DogSport" ) or die ("Couldn't connect to server");

    echo mysqli_real_escape_string($con, $text);
?>
Amali
  • 53
  • 1
  • 7
  • 3
    use it as `$text = "I'm \"X-MAN\"";` – Saty Apr 20 '16 at 07:11
  • 1
    The parse error has nothing to do with `mysqli_real_escape_string`. PHP can’t parse the string literal `"I'm "X-MAN""` because it assumes it ends with the `"` and then sees a token `X` that it can’t parse. To create a string literal with a `"` inside, you need to escape it using the backslash, as others have noted. Note that the backslash will not end up in the string contents, it’s just needed for inputting the string. That’s why you still need `mysqli_real_escape_string`. – Raphael Schweikert Apr 20 '16 at 07:27

3 Answers3

0

Either change

$text = "I'm "X-MAN"";

To

$text = "I'm \"X-MAN\"";

OR To:

$text = 'I\'m "X-MAN"';

The string has single/double quotes closing before string completion.

So, escape intermediate single/double quotes.

Pupil
  • 23,141
  • 5
  • 40
  • 62
  • I understand that. But doesn't mysqli_real_escape_string do that? As I know, it adds "\" before special characters. – Amali Apr 20 '16 at 07:15
0

First you need to escape your quotes as

$text = "I'm \"X-MAN\"";

Make your connection using port as

$con = mysqli_connect( "localhost", "root", "P@ssw0rd", "DogSport","3306" ) or die ("Couldn't connect to server");// pass fifth parameter is your port 

To check error in connection use

if ($con->connect_errno) {
    printf("Connect failed: %s\n", $con->connect_error);
    exit();
}
Saty
  • 21,683
  • 7
  • 29
  • 47
  • why do I need to escape my quotes? It is done using mysqli_real_escape_string. Am I right? As I know, it adds "\" before special characters. – Amali Apr 20 '16 at 07:23
  • Better use bind statement!! We use escape to make a valid syntax for `$text` only – Saty Apr 20 '16 at 07:26
0

It is because the String in your $text variable is itself an error. If you run only this line of code you will have the same Parse error.

<?php
    $text = "I'm "X-MAN"";
?>

So if you want to have a quoted string you could do one of the following:

  1. $text = "I'm 'X-MAN'";
  2. $text = 'I"m "X-MAN"';

Thus your final code will be:

<?php
    $text = "I'm 'X-MAN'";
    $con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "DogSport" ) or die ("Couldn't connect to server");
    echo mysqli_real_escape_string($con, $text);
?>

And the escape string will be I\'m \'X-MAN\' or I\"m \"X-MAN\" respectfully.

Hope this will make you clear.

Siddiqui Noor
  • 787
  • 1
  • 7
  • 30