Search code examples
phpmysqlsqlpdoslim

Only variables should be passed by reference - when using LIMIT with bindParam


I want use LIMIT with bindParam so I build this query:

$app->get('/contact/get_contacts/{contact_number}', function (Request $request, Response $response, array $args)
{
    $query = "SELECT * FROM contact LIMIT :contact_number";
    $sql->bindParam("contact_number", intval($args["contact_number"]), PDO::PARAM_INT);
    $sql->execute();
    $result = $sql->fetchAll();
    return $response->withJson($result);
});

I get this notice:

Only variables should be passed by reference

What I did wrong? I'm using Slim Framework with PDO


Solution

  • You need to change:

    $sql->bindParam("contact_number", intval($args["contact_number"]), PDO::PARAM_INT);
    

    with,

    $sql->bindParam(":contact_number", $args["contact_number"], PDO::PARAM_INT);
    
    • I have added the missing : before the parameter name.
    • I have removed the intval function call, if you still want to use the function then use it outside of the bindParam function call.

    As per the function definition:

    public bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
    

    the bound parameter is a variable by reference (&$variable).

    Reading Material

    bindParam