0

I'm hitting my head to a wall... This is a fraction of my code:

$stmt = $db->prepare("SELECT vote,id FROM votes WHERE post_id = ? AND user_id = ? "); 
$stmt->bind_param('ii', $post_id, $user_id);
$stmt->execute(); 
$stmt->store_result();
$stmt->bind_result($result, $vote_id);
$stmt->fetch();
$num_rows = $stmt->num_rows;
$stmt->close();

if ($num_rows>=1)
{

if ($result!==$vote)   
{        
$stmt = $db->prepare("UPDATE votes SET vote = ? WHERE id=?"); 
$stmt->bind_param('ii', $vote, $vote_id);
$stmt->execute();
$stmt->close();
}

else if ($result==$vote) 
{
$stmt = $db->prepare("UPDATE votes SET vote = 0 WHERE id=?"); 
$stmt->bind_param('i', $vote_id);
$stmt->execute();
$stmt->close();
}    
}

No errors are shown, the script works just fine until it reaches ELSE IF part. It doesn't update although $vote value is the same as in a database.

1
  • 1
    you don't need an else **if** just an else, its either going to be match or not Commented Dec 4, 2013 at 23:23

1 Answer 1

3

!== is a strict comparison operator, and this statement is saying that $result must not be identical (in type as well as value) to $vote. You don't need to be that specific for this.

if ($result!==$vote) 

What you should be doing is this:

if ($result != $vote) // only one equal sign, not two
{
   ...
} else { // they are equal implicitly, no need to redefine the ==
    ...
}  
Sign up to request clarification or add additional context in comments.

6 Comments

+1 can only assume $vote is an integer whilst any result from bind_result / fetch will be a string
@Phil, yeah $vote is either 1 or -1... So the reason of this issue is different data types? And how should I make them both int?
@SauliusSlavinskas Just use != instead, it automatically converts variable types and compares them.
@scrowler God bless ya! Just tried your suggestion and it works. Thank you so much!
@SauliusSlavinskas For completeness, you can also cast $result to an integer via (int) $result
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.