Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't pass a constant variable by reference with $stmt->bind_param()?

This is my code snippet:

private function add_user_limit()
{
    global $mysqli;
    $stmt = $mysqli->prepare("INSERT INTO `user_limits` (user_ip, downloads_left) VALUES (?, ?)");
    $stmt->bind_param("si", $this->user_ip, DEFAULT_USER_LIMIT);
    $stmt->execute();
    if($stmt->affected_rows == 0)
        throw new Exception("Couldn't add new user to the user_limits table");
    $stmt->close();
    $this->downloads_left = DEFAULT_USER_LIMIT;
}

DEFAULT_USER_LIMIT is defined as 8, but with the above code I get this error:

Fatal error: Cannot pass parameter 3 by reference in C:\xampp\htdocs\classes\limits.class.php on line 38

But if I do this:

private function add_user_limit()
{
    global $mysqli;
    $stmt = $mysqli->prepare("INSERT INTO `user_limits` (user_ip, downloads_left) VALUES (?, ?)");
    $user_limit = DEFAULT_USER_LIMIT; // For some reason we can't pass a constant to bind_param
    $stmt->bind_param("si", $this->user_ip, $user_limit);
    $stmt->execute();
    if($stmt->affected_rows == 0)
        throw new Exception("Couldn't add new user to the user_limits table");
    $stmt->close();
    $this->downloads_left = DEFAULT_USER_LIMIT;
}

It works. I was just wondering why this happens, as it doesn't really make sense to me. I don't see any reason why bind_param() can't take a constant variable as a parameter.

Thanks!

like image 342
Josh Avatar asked Jun 09 '26 10:06

Josh


1 Answers

Quite simply, it's because you can't pass a constant by reference, and there would be no point in doing so, as it is immutable. Constants, by the way, are not variables; it's right there in the name.

like image 96
Dereleased Avatar answered Jun 11 '26 23:06

Dereleased