asdasdasdas
asdasdasdas

Reputation: 11

PHP is changing the value of my variable because i bind it as a mysqli parameter?

im tracking down a weird bug where a variable i have is being changed at some point, and this is where I found the problem:

echo "2. page is $page<br>";
$h = $page;
//Ok everything is done. Now need to update the view counter
$query = "UPDATE pages SET views=views+1 WHERE id=? LIMIT 1";
if($stmt = $db -> prepare($query))
{
    $stmt -> bind_param("i", $page);
    $stmt ->execute();
    $stmt ->close();
}
else
    dberror();
echo "3. page is $page<br>";
$page = $h;
echo "4. page is $page<br>";

So I am getting this:

2. page is page
3. page is 0
4. page is page

I just added in that $h variable to try and fix the problem and it worked. So for some reason the sql query is destrying my page variable. Does anyone know why this would happen?

Upvotes: 1

Views: 68

Answers (2)

Ben James
Ben James

Reputation: 125147

You bound it as an integer: $stmt->bind_param("i", $page);, but it was actually a string: "page".

bind_param binds a reference to the actual variable, not a copy of it, to the statement. So it must modify the variable, converting it to an integer to work as a bound integer parameter.

The integer value of "page" (in fact, of any string that contains no digits) is 0, so that's why you see it becoming 0.

Upvotes: 4

mip
mip

Reputation: 8713

$page is passed by reference in bind_param("i", $page); thus as others mentioned , PHP converted it to int and that's why it was destroyed

Upvotes: 0

Related Questions