I've made a like button on my site (which uses ExpressionEngine), and it works. However when I put almost identical code on another page, the like button's text is always what it should have been on the last page (the opposite to what it should be, though refreshing the page puts it right, so I can't just flip the values. Here's the code that works:
<?php
$DB1 = $this->EE->load->database('ext_db', TRUE);
$mapID = "{entry_id}";
$ipAddress = $_SERVER['REMOTE_ADDR'];
$thisquery = "SELECT * FROM mapLikes WHERE ipAddress = '$ipAddress' AND mapID = '$mapID'";
$q = $DB1->query($thisquery);
$results = $q->result_array();
foreach ($q->result() as $row)
{
$liked = $row->liked;
}
$buttontext = 'Like';
$buttonimage = "1";
if ($liked == "1") {
$buttontext = 'Unlike';
$buttonimage = "2";
}
if($_POST['like']) {
if ($liked == "1") {
$thisquery = "DELETE FROM mapLikes WHERE mapID = '$mapID' AND ipAddress = '$ipAddress'";
$DB1->query($thisquery);
} else {
$thisquery = "INSERT INTO mapLikes (mapLikeID, mapID, liked, ipAddress) VALUES ('null', '$mapID', '1', '$ipAddress')";
$DB1->query($thisquery);
}
}
?>
And the code that doesn't:
<?php
$DB1 = $this->EE->load->database('ext_db', TRUE);
$mapID = "{segment_3_category_id}";
$ipAddress = $_SERVER['REMOTE_ADDR'];
$thisquery = "SELECT * FROM categoryLikes WHERE ipAddress = '$ipAddress' AND mapID = '$mapID'";
$q = $DB1->query($thisquery);
$results = $q->result_array();
foreach ($q->result() as $row)
{
$liked = $row->liked;
}
$buttontext = 'Like';
$buttonimage = "1";
if ($liked == "1") {
$buttontext = 'Unlike';
$buttonimage = "2";
}
if($_POST['like']) {
if ($liked == "1") {
$thisquery = "DELETE FROM categoryLikes WHERE mapID = '$mapID' AND ipAddress = '$ipAddress'";
$DB1->query($thisquery);
} else {
$thisquery = "INSERT INTO categoryLikes (categoryLikeID, mapID, liked, ipAddress) VALUES ('null', '$mapID', '1', '$ipAddress')";
$DB1->query($thisquery);
}
}
?>
As you can see, the only difference between the two pieces of code are the $mapID and the queries. Yet for some reason one works and the other doesn't. Anyone have any idea what might be going on? I'm thinking this is more a php problem than an ExpressionEngine one.
Figured it out now, and also realised the first bit of code had the same issues as the second. What I did was I made the POST script set the button state, like so:
if($_POST['like']) {
if ($liked == "1") {
$thisquery = "DELETE FROM mapLikes WHERE mapID = '$mapID' AND ipAddress = '$ipAddress'";
$DB1->query($thisquery);
$buttontext = 'Like';
$buttonimage = "1";
} else {
$thisquery = "INSERT INTO mapLikes (mapLikeID, mapID, liked, ipAddress) VALUES ('null', '$mapID', '1', '$ipAddress')";
$DB1->query($thisquery);
$buttontext = 'Unlike';
$buttonimage = "2";
}
}