Search code examples
phpmysqlfunctionvariablesquotations

PHP - create function issue


I'm trying to understand this code and I can't :(

$time = date('Y-m-d', strtotime('-30 days'));
$what = create_function('$a', 'return $a.'.'"'." AND date > '$time'".'"'.';');

Why does the $time variable get passed successfully in this created function, but when I try:

$limit = 10;
$what = create_function('$a', 'return '.'"'." LIMIT '$limit'".'"'.';');

$limit doesn't ?

ps: if I try $what = create_function('$a', 'return '.'"'." LIMIT 10".'"'.';'); it works...


Solution

  • The code can be much simplified:

    $what = create_function('$a', "return \"LIMIT $limit\";");
    

    or

    $what = create_function('$a', 'return "LIMIT ' .  $limit .'";');
    

    The code should work. Note that the number after LIMIT must not be enclosed in quotes in the SQL syntax.

    But as you are creating a function, you could also pass $limit as parameter to the function:

    $what = create_function('$limit', 'return "LIMIT $limit";');
    $str = $what(10);
    

    or don't use create_function at all and just do string concatenation directly:

    $str = 'LIMIT ' . $limit;