0

For some reason I can't make my code work like I want it to.

$Check = $_POST['phrase'];

    try{ $db=new readPDO('testDB'); $sql=('

        SELECT entry, ID
        FROM test
        WHERE entry = "$Check "

        ');

$statement=$db->prepare($sql);
$statement->execute();

If I try this:

$Check = $_POST['phrase'];

    try{ $db=new readPDO('testDB'); $sql=('

        SELECT entry, ID
        FROM test
        WHERE ID= "$Check "

        ');

$statement=$db->prepare($sql);
$statement->execute();

The GET is a number which works fine, but it doesn't work with strings.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
user3066588
  • 111
  • 1
  • 7

1 Answers1

0

As documented under Strings:

A string literal can be specified in four different ways:

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ').

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?
// [ deletia ]

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

 Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

[ deletia ]

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

In your case, $sql is assigned the value of a single-quoted string literal in which the $Check variable will not be expanded (whilst it is itself enclosed by double-quotes therein, so far as the PHP parser is concerned it is still a single-quoted string literal).

Using a double-quoted string literal would provide variable expansion. If you still wish to quote $Check within the string literal using double-quotes, then they would have to be escaped (with backslashes):

$sql = "
    SELECT entry, ID
    FROM test
    WHERE entry = \"$Check \"
";

Alternatively, one could now quote $Check using single quotes (since MySQL recognises both forms of string quoting, provided that ANSI_QUOTES is disabled):

$sql = "
    SELECT entry, ID
    FROM test
    WHERE entry = '$Check '
";

Note that the trailing space within the quotes will be parsed by MySQL as part of the string, which may not be your intention.

Note also that this code is vulnerable to SQL injection attacks (and also bugs if $Check happens to contain certain characters). You should read @deceze's blog article The Great Escapism (Or: What You Need To Know To Work With Text Within Text) to understand this better; and then How can I prevent SQL injection in PHP? to understand how to fix it.

Community
  • 1
  • 1
eggyal
  • 122,705
  • 18
  • 212
  • 237