I have a forum thread file thread.php
that gets topic ID information.
Example:
thread.php?id=781
I'm trying to create a unique views setup, but I have no idea if this is actually feasible:
thread.php
:
topicId = <?php echo $_GET['id']; ?>;
if ($.cookie("unique"+topicId)!=="1") {
$.cookie("unique"+topicId,1,{expires: 1000, path: '/'}); // create cookie if it doesn't exist
$.post('unique.php',{id:topicId}); // update thread unique views
}
unique.php
// connection stuff
$id = mysqli_real_escape_string($conn,$_POST['id']);
mysqli_query($conn,"UPDATE topics SET unique_views=unique_views+1 WHERE id='$id'");
This will create a new cookie for each different thread. So if the user views 100 threads, they'll have 100 cookies stored. I'm worried if creating a new cookie for each thread is too much. Is that okay or is there a better way to do it?
Even being possible, that is a waste of resources. You should serialize your data into a single cookie using JSON, for example.
In Javascript you can encode your topics array into a JSON string with JSON.stringify:
$.cookie("cookie_name", JSON.stringify(topicsId_array));
Then you can get the data with JSON.parse:
var topicsId_array = JSON.parse($.cookie("cookie_name"));
Remember you can use the push JS method to add elements to an array (http://www.w3schools.com/jsref/jsref_push.asp), so you could get the data from the cookie add the new Id with push and then save it with stringify.
To finish, you should care about duplicates. If you don't want them when using push, you can use https://api.jquery.com/jQuery.unique/ to clear the array or use a own JS function such as:
function unique(array_source)
{
var array_destination = [];
var found = false;
var x, y;
for (x=0; x<array_source.length; x++)
{
found = false;
for (y=0; y<array_destination.length; y++)
{
if (array_source[x] === array_destination[y])
{
found = true;
break;
}
}
if (!found)
{
array_destination.push(array_source[x]);
}
}
return array_destination;
}
var topicsId_array = ['aaa', 'bbb', 'ccc', 'aaa'];
topicsId_array = unique(topicsId_array);
And in the end, something like this should work:
var topicsId_array = JSON.parse($.cookie("cookie_name"))
topicsId_array.push("your_new_id");
topicsId_array = $.unique(topicsId_array);
$.cookie("cookie_name", JSON.stringify(topicsId_array));;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With