PHP: Store last viewed items in session array - php

I have a simple function that do this:
1) User view some image and image_id is stored in session array
2) Then user can see the last 10 viewed images
Currently my function is this:
function lastSeen($image_id){
if(!isset($_SESSION['lastSeen'])){
$_SESSION['lastSeen'] = array($image_id);
}else{
$tmpSession = array_unique($_SESSION['lastSeen']);
if(count($tmpSession) > 9){
$tmpSession = array_slice($tmpSession,1);
}
$tmpSession[] = $image_id;
$_SESSION['lastSeen'] = array_unique($tmpSession);
}
return true;
}
This function works but the problem is that, if a user view one image more than one time, then in session are saved only 9 items.
Can anybody help me solve this problem? Maybe the whole function needs to be rewrite it...

You probably want to remove extraneous entries as the very last thing, and also only if it's more than 10 entries:
else {
$tmpSession = $_SESSION['lastSeen'];
$tmpSession[] = $image_id;
$tmpSession = array_unique($tmpSession);
if(count($tmpSession) > 10){
$tmpSession = array_slice($tmpSession,1);
}
$_SESSION['lastSeen'] = $tmpSession;
}

If you wouldn't mind that the order of images doesn't change, when the user views one image twice, then I would go with this simple solution. Just add line like this:
if (in_array($image_id, $tmpSession)) return true;
So your function would look like this:
function lastSeen($image_id){
if(!isset($_SESSION['lastSeen'])){
$_SESSION['lastSeen'] = array($image_id);
} elseif (in_array($image_id, $_SESSION['lastSeen'])) {
return true;
} else {
$tmpSession = array_unique($_SESSION['lastSeen']);
if(count($tmpSession) > 9){
$tmpSession = array_slice($tmpSession,1);
}
$tmpSession[] = $image_id;
$_SESSION['lastSeen'] = array_unique($tmpSession);
}
return true;
}

Another implementation of your function could be:
function lastSeen($image_id){
if(!isset($_SESSION['lastSeen']) || !is_array($_SESSION['lastSeen'])){
$_SESSION['lastSeen'] = array();
}
if(!in_array($image_id, $_SESSION['lastSeen']){
array_push($_SESSION['lastSeen'], $image_id);
}
if(sizeof($_SESSION['lastSeen']) > 10){
array_shift($_SESSION['lastSeen']);
}
}

If you want a function that stores the last visited image as the last item in the array, then just replace:
$tmpSession = array_slice($tmpSession,1);
with the following line:
if (in_array($image_id,$tmpSession))
array_splice($tmpSession, array_search($image_id, $tmpSession), 1);
else
$tmpSession = array_slice($tmpSession, 1);
The result function would look like:
function lastSeen($image_id) {
if (!isset($_SESSION['lastSeen'])) {
$_SESSION['lastSeen'] = array($image_id);
} else {
$tmpSession = array_unique($_SESSION['lastSeen']);
if (count($tmpSession) > 9){
if (in_array($image_id,$tmpSession))
array_splice($tmpSession, array_search($image_id, $tmpSession), 1);
else
$tmpSession = array_slice($tmpSession, 1);
}
$tmpSession[] = $image_id;
$_SESSION['lastSeen'] = array_unique($tmpSession);
}
return true;
}

Related

Problem in code that must not repeat the same number in PHP

I've written this function that returns a time(number )that must not exist in the same day in the database which means that the same time must not be repeated but when I execute it the time(number) is repeated
can you help me sort this one out?
screen shots of the tables
https://files.fm/u/9aw9yc8x
note: the table is empty and it will be filled when the entire code is executed I have just posted the function that must not repeat the time.
function checkTime($className,$day,$conn){
global $numberLimet,$Daily,$UserLimt,$exist;
$sqlHoure = "SELECT * from schedule WHERE classname='".$className."'";
$hourQuery = mysqli_query($conn,$sqlHoure);
$h = array();
while ($hour = mysqli_fetch_assoc($hourQuery)){
$h[$hour['hour']] = $hour['day1'];
// array_search();
}
$number = rand(1,7);
if(array_search($day,$h) && array_key_exists($number,$h)){
return 'error';
}else{
if($hour['hour'] != $number && $hour['day1'] != $day){
$numberLimet++;
if($numberLimet == $Daily){
$UserLimt = 1;
$FristAdd = false;
echo("UserLimt" . $UserLimt);
return 'errorLimit';
}else{
return $number;
}
}else{
}
}
return $h;
}

php validation from array form

I have a code like this
First looping count how many post the array:
for($i = 0; $i < $jumlah_qty ;$i++) {
if(!empty($qty[$i]) && !empty($id_cat[$i])) {
Insert booking:
$insert_booking_hd = $user_class->select($az);
$id_cates = $id_cat[$i];
for($b = 0;$b<$qty[$i];$b++) {
First validation if $_POST[$id_cates) is set run this code:
if(isset($_POST[$id_cates."".$b])){
$id_seat = $_POST[$id_cates."".$b];
Find the seat number in $select_seat and find if seat number is exist in $seat_number:
$select_seat = $user_class->select($query);
$seat_number = $user_class->select($querys);
$row_seat = $user_class->numrows($select_seat);
$row_seat2 = $user_class->numrows($seat_number);
if($row_seat>0) {
$update_seat = $user_class->update($update_false);
$bol[$b] = FALSE;
} else {
if( $row_seat2>0 ) {
$insert_booking_dt = $user_class->insert($insert);
$update_seat = $user_class->update($update_true);
$bol[$b] = TRUE;
} else {
$bol[$b] = FALSE;
}
}
} else {
$insert_booking_dt = $user_class->insert($insert_without_seat);
$bol[$b] = TRUE;
}
if($bol[$b]) {
echo "FALSE";
header("location:../../../print.php?id=$id_booking");
}
else {
echo "WRONG";
header("location:../../../event.php?msg=Same seat number");
}
}
}
}
Anything wrong with my php validation?
Because if I input array of $id_seat it will always redirect to print.php although validation is FALSE
for example if I input 3 array and then I echo FALSE WRONG FALSE FALSE
still redirect to print.php not to event.php
How can I read if one of array is get WRONG and then redirect to event.php?
How can I read if one of array is get WRONG and then redirect to event.php?
You may break out of for-loops.
Instead of:
else {
echo "WRONG";
header("location:../../../event.php?msg=Same seat number");
}
You could try:
else {
echo "WRONG";
header("location:../../../event.php?msg=Same seat number");
break 2;
}

PHP recently viewed script to session array

I've been given this bit of code:
if(isset($_GET['viewevent'])) {
if(count($_SESSION['e_lastviewed']) == 0) {
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
} else if(!in_array($_GET['viewevent'], $_SESSION['e_lastviewed'])) {
$_SESSION['e_lastviewed'][2] = $_SESSION['e_lastviewed'][1];
$_SESSION['e_lastviewed'][1] = $_SESSION['e_lastviewed'][0];
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
}
}
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}
It apparently saves ID's of recently viewed items, so i need to put these id's into an array.
Would this work?
$my_array = array($_SESSION['e_lastviewed'][2],$_SESSION['e_lastviewed'][1],$_SESSION['e_lastviewed'][0]);
I've ran it but it displays blank results (not sure if thats due to me not doing it right or incomplete code...Have i missed something? I'm not sure if i completley understand the script i was given...
try this:
if ( !isset($_SESSION['e_lastviewed']) )
$_SESSION['e_lastviewed'] = array();
// alt: while(count($_SESSION['e_lastviewed']) > 2 ) {
if(count($_SESSION['e_lastviewed']) > 2 ) {
array_shift($_SESSION['e_lastviewed']); // drop off from 3
array_unshift($_SESSION['e_lastviewed'],$_GET['viewevent']); // insert in the beginning
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}

if else simple beginner issue

Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}

Is there a piece of public code available to create a page index using PHP?

I have a MySQL table holding lots of records that i want to give the user access to. I don't want to dump the entire table to the page so i need to break it up into 25 records at a time, so i need a page index. You have probably seen these on other pages, they kind of look like this at the base of the page:
< 1 2 3 4 5 6 7 8 9 >
For example, when the user clicks on the '4' link, the page refreshes and the offset is moved on (4th page x 25 records). Here is what i already have:
function CreatePageIndex($ItemsPerPage, $TotalNumberOfItems, $CurrentOffset, $URL, $URLArguments = array())
{
foreach($URLArguments as $Key => $Value)
{
if($FirstIndexDone == false)
{
$URL .= sprintf("?%s=%s", $Key, $Value);
$FirstIndexDone = true;
}
else
{
$URL .= sprintf("&%s=%s", $Key, $Value);
}
}
Print("<div id=\"ResultsNavigation\">");
Print("Page: ");
Print("<span class=\"Links\">");
$NumberOfPages = ceil($TotalNumberOfItems / $ItemsPerPage);
for($x = 0; $x < $NumberOfPages; $x++)
{
if($x == $CurrentOffset / $ItemsPerPage)
{
Print("<span class=\"Selected\">".($x + 1)." </span>");
}
else
{
if(empty($URLArguments))
{
Print("".($x + 1)." ");
}
else
{
Print("".($x + 1)." ");
}
}
}
Print("</span>");
Print(" (".$TotalNumberOfItems." results)");
Print("</div>");
}
Obviously this piece of code does not create a dynamic index, it just dumps the whole index at the bottom of the page for every page available. What i need is a dynamic solution that only shows the previous 5 pages and next 5 pages (if they exist) along with a >> or something to move ahead 5 or so pages.
Anybody seen an elegant and reusable way of implementing this as i feel i'm re-inventing the wheel? Any help is appreciated.
Zend Framework is becoming a useful collection and includes a Zend_Paginator class, which might be worth a look. Bit of a learning curve and might only be worth it if you want to invest the time in using other classes from the framework.
It's not too hard to roll your own though. Get a total count of records with a COUNT(*) query, then obtain a page of results with a LIMIT clause.
For example, if you want 20 items per page, page 1 would have LIMIT 0,20 while page 2 would be LIMIT 20,20, for example
$count=getTotalItemCount();
$pagesize=20;
$totalpages=ceil($count/$pagesize);
$currentpage=isset($_GET['pg'])?intval($_GET['pg']):1;
$currentpage=min(max($currentpage, 1),$totalpages);
$offset=($currentpage-1)*$pagesize;
$limit="LIMIT $offset,$pagesize";
It's called Pagination:
a few examples:
A nice one without SQL
A long tutorial
Another tutorial
And Another
And of course.. google
How about this jQuery-plugin?
So all the work is done on the clientside.
http://plugins.jquery.com/project/pagination
demo: http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
Heres an old class I dug out that I used to use in PHP. Now I handle most of it in Javascript. The object takes an array (that you are using to split the stack into pages) and return the current view. This can become tedious on giant tables so keep that in mind. I generally use it for paging through small data sets of under 1000 items. It can also optionally generate your jump menu for you.
class pagination {
function pageTotal($resultCount, $splitCount) {
if (is_numeric($resultCount) && is_numeric($splitCount)) {
if ($resultCount > $splitCount) {
$pageAverage = (integer)$resultCount / $splitCount;
$pageTotal = ceil($pageAverage);
return $pageTotal;
} else {
return 1;
}
} else {
return false;
}
}
function pageTotalFromStack($resultArray, $splitCount) {
if (is_numeric($splitCount) && is_array($resultStack)) {
if (count($resultStack) > $splitCount) {
$resultCount = count($resultStack);
$pageAverage = (integer)$resultCount / $splitCount;
$pageTotal = ceil($pageAverage);
return $pageTotal;
} else {
return 1;
}
} else {
return false;
}
}
function makePaginationURL($preURL, $pageTotal, $selected=0, $linkAttr=0, $selectedAttr=0) {
if (!empty($preURL) && $pageTotal >= 1) {
$pageSeed = 1;
$passFlag = 0;
$regLink = '<a href="{url}&p={page}"';
if (is_array($linkAttr)) $regLink .= $this->setAttributes($linkAttr); //set attributes
$regLink .= '>{page}</a>';
$selLink = '<a href="{url}&p={page}"';
if (is_array($selectedAttr)) $selLink .= $this->setAttributes($selectedAttr); //set attributes
$selLink .= '>{page}</a>';
while($pageSeed <= $pageTotal) {
if ($pageSeed == $selected) {
$newPageLink = str_replace('{url}', $preURL, $selLink);
$newPageLink = str_replace('{page}', $pageSeed, $newPageLink);
} else {
$newPageLink = str_replace('{url}', $preURL, $regLink);
$newPageLink = str_replace('{page}', $pageSeed, $newPageLink);
}
if ($passFlag == 0) {
$passFlag = 1;
$linkStack = $newPageLink;
} else {
$linkStack .= ', ' . $newPageLink;
}
$pageSeed++;
}
return $linkStack;
} else {
return false;
}
}
function splitPageArrayStack($stackArray, $chunkSize) {
if (is_array($stackArray) && is_numeric($chunkSize)) {
return $multiArray = array_chunk($stackArray, $chunkSize);
} else {
return false;
}
}
}

Categories