Looping the slideshow within the search results

Hi Everyone, I am a PHP newbie. I have a simple search page for my gallery.

if(isset($_GET['form_id:search'])) {
$images_dir = 'images';
$q = $_GET['q'];
$sql = mysqli_query( $mysqli,"
SELECT
created_date
, img_description
, g_description
, img_caption
, img_filename
, category_name
, img_keywords
FROM
g_images
WHERE
keywords   like '%". mysqli_real_escape_string($mysqli,$c) ."%'
OR 
img_caption like '%". mysqli_real_escape_string($mysqli,$c) ."%'
");

Then I create a simple link to display the search results. The results show up as thumbnails.

<a href="'.html_escape('viewgallery.php?'.http_build_query($p_search),'UTF-8').'"><img src="'.$images_dir. '/tb_'.$rows['img_filename'].'" alt="'.htmlspecialchars($rows['img_caption']).'"></a>

When I click on this thumbnail it takes me to the larger image. And there is a ‘next’ button that takes me to the next image.

$result_final .= '<div class="image"><table><tr><td><table class="image"><tr><td><a href="' . html_escape('gallery.php?' . http_build_query($p_next), 'UTF-8') . '">
<img src="'. $images_dir . '/' .$img_filename.'"  alt=" ' . $img_keywords . '"></a>

But when I click on the ‘next’ button it takes me out of the search result and takes me to the next image in the database NOT to the next image in the search result. How can I write a code to keep me looping within the search result set ? Any pointers to the right direction will be helpful…

Thank you.

where is $p_next defined? That looks to be the value you need to change (from “next in gallery” to “next in search”)

Thanks StaLion, the $p_next is an array made up URL variables which looks like this.

$p_next = array(
‘catname’ => $catname,
‘piccaption’ => $caption_array[$next],
)

Where $next = $key + 1;

and

$key = array_search($piccaption, $caption_array);

What I don’t know how to do is how I can connect/combine search results with the image slideshow…

Down the rabbit hole…

So where does $caption_array and $catname get filled out? (seems weird to pass a caption on the URL, but whatever.)

It may be easier to put your entire gallery.php in in this case.

Thank you StarLion, here is my code… this might be a very bad example of PHP code, I found this old code and trying to make this work. Just to let you know this code does not include mysqli and html escape methods I used later on.

[quote=“StarLion, post:4, topic:98154, full:true”](seems weird to pass a caption on the URL, but whatever.)
[/quote] why do you say that it is weird to pass a caption on the URL ( I am asking this so I could learn from you…I am new , I would like to know about best practices…) … I did this so that I can have a pretty URL including my caption. Thanks for any help…

My code…

// initialization
$p_cap         = "";
$p_description = "";
$p_keywords    = "";
$g_description = "";
$result_array  = array();
$counter       = 0;
$cname         = isset($_GET['cname']) ? ($_GET['cname']) : 0;
$pcap          = isset($_GET['pcap']) ? (urldecode($_GET['pcap'])) : 0;
$cname         = str_replace("-", " ", $cname);
// Category Listing
if (empty($cname) && empty($pcap)) {
    $number_of_categories_in_row = 2;
    $result                      = mysql_query("
            SELECT
                 c.category_name
                 ,c.category_image
                , COUNT(p.img_cap)
            FROM
                gallery_category as c
            LEFT JOIN
                gallery_imgs as p
            ON
                p.category_name = c.category_name
            GROUP BY
                c.category_name");
    while ($row = mysql_fetch_array($result)) {
        $row[0]         = trim($row[0]);
        $row[0]         = str_replace(" ", "-", $row[0]);
        $row[0]         = str_replace("'", "%27", $row[0]);
        $result_array[] = "<div class=cthumbs><a href='gallery.php?cname=" . $row[0] . "'><br/><img src='/imgs/categoryimages/" . $row[1] . "' height='153px' width='230px' ><br/>
<span class=cname>" . $row[0] . "</span></a></div>";
    }
    mysql_free_result($result);
    $result_final = "<div class=cpage><div class=categories><table class=categoryview><tr>\n";
    foreach ($result_array as $category_link) {
        if ($counter == $number_of_categories_in_row) {
            $counter = 1;
            $result_final .= "\n</tr>\n<tr>\n";
        } else
            $counter++;
        $result_final .= "\t<td>" . $category_link . "</td>\n";
    }
    if ($counter) {
        if ($number_of_categories_in_row - $counter)
            $result_final .= "\t<td colspan='" . ($number_of_categories_in_row - $counter) . "'></td>\n";
        $result_final .= "</tr></table></div><!-- .cpage --></div>    ";
    }
}
// Thumbnail Listing
else if ($cname && empty($pcap)) {
    $number_of_thumbs_in_row = 3;
    // If current page number, use it 
    // if not, set one! 
    if (!isset($_GET['page'])) {
        $page = 1;
    } else {
        $page = $_GET['page'];
    }
    // Define the number of results per page 
    $max_results = 180;
    // Figure out the limit for the query based 
    // on the current page number. 
    $from        = (($page * $max_results) - $max_results);
    $result      = mysql_query("SELECT 
          img_cap
        , img_filename 
        , category_name
        , gallery_description FROM gallery_imgs WHERE category_name='" . addslashes($cname) . "' LIMIT $from, $max_results 
        ");
    $nr          = mysql_num_rows($result);
    if (empty($nr)) {
        $result_final = "\t<tr><td>No imgs found</td></tr>\n";
    } else {
        while ($row = mysql_fetch_array($result)) {
            $row[0]         = trim($row[0]);
            $row[0]         = str_replace(" ", "-", $row[0]);
            $row[0]         = str_replace("'", "%27", $row[0]);
            $cname          = str_replace(" ", "-", $cname);
            $result_array[] = "<a href='gallery.php?cname=$cname&pcap=" . $row[0] . "'><img src='" . $images_dir . "/tb_" . $row[1] . "' alt='" . $row[0] . "' /></a>";
        }
        $cname  = str_replace("-", " ", $cname);
        $result = mysql_query("SELECT category_name FROM gallery_category WHERE category_name='" . addslashes($cname) . "'");
        $nr     = mysql_num_rows($result);
        list($category_name) = mysql_fetch_array($result);
        mysql_free_result($result);
        ##$g_description = $gallery_description;
        $result_final = "<div class=thumbsPage><div class=link><a href='gallery.php'>Albums</a>
           <span class=arrow>&gt;&gt</span><a href='gallery.php?cname=$cname'>$category_name</a><br><br></div>
           <div class=des><br><br></div><tr><td align=center valign=middle><div class=thumbs><table><tr>\n";
        foreach ($result_array as $thumbnail_link) {
            if ($counter == $number_of_thumbs_in_row) {
                $counter = 1;
                $result_final .= "\n</tr>\n<tr>\n";
            } else
                $counter++;
            $result_final .= "\t<td>" . $thumbnail_link . "</td>\n";
        }
        if ($counter) {
            if ($number_of_thumbs_in_row - $counter)
                $result_final .= "\t<td colspan='" . ($number_of_thumbs_in_row - $counter) . "'>&nbsp;</td>\n";
            $result_final .= "</tr></table></td></tr></table></div></div>";
            // Figure out the total number of results in DB:  
            $total_results = mysql_query("SELECT COUNT(*) FROM gallery_imgs WHERE category_name='" . addslashes($cname) . "'");
            if (!$total_results) {
                die('Could not query:' . mysql_error());
            }
            $total_results = mysql_result($total_results, 0);
            // Figure out the total number of pages. Always round up using ceil() 
            $total_pages   = ceil($total_results / $max_results);
            if ($total_pages > 1) {
                // build links if more than one page
                // Build Page Number Hyperlinks 
                $result_final .= "<div class=plinks><tr><td colspan='" . $number_of_thumbs_in_row . "' class='tcat'>\n&nbsp;&nbsp;";
                // Build Previous Link 
                if ($page > 1) {
                    $prev = ($page - 1);
                    $result_final .= "\n<a href=\"" . $_SERVER['PHP_SELF'] . "?cname=$cname&page=$prev\" title='Previous Page'>&lt;&lt;PREVIOUS PAGE</a>";
                }
                for ($i = 1; $i <= $total_pages; $i++) {
                    if (($page) == $i) {
                        $result_final .= "&nbsp; $i";
                    } else {
                        $result_final .= "\n<a href=  \"" . $_SERVER['PHP_SELF'] . "?cname=$cname&page=$i\" title='Page " . $i . "'class=pagenos>$i</a>";
                    }
                }
                // Build Next Link 
                if ($page < $total_pages) {
                    $next = ($page + 1);
                    $result_final .= "\n<a href=\"" . $_SERVER['PHP_SELF'] . "?cname=$cname&page=$next\" title='Next Page'>NEXT PAGE<span class=arrow>&gt;&gt</span></a>";
                }
                $result_final .= "\n</td></tr></div>";
            } else {
                $result_final .= "\n";
            }
        }
    }
}
// display previous and next links if more than one img 
else if ($pcap) {
    $pcap   = str_replace("-", " ", $pcap);
    $pcap   = str_replace("%27", "'", $pcap);
    $pcap   = str_replace("\\", "", $pcap);
    $result = mysql_query("SELECT img_cap, img_description, img_filename,img_keywords FROM gallery_imgs WHERE img_cap='" . addslashes($pcap) . "'");
    list($img_cap, $img_description, $img_filename, $img_keywords) = mysql_fetch_array($result);
    $nr = mysql_num_rows($result);
    mysql_free_result($result);
    $p_cap         = $img_cap;
    $p_description = $img_description;
    $p_keywords    = $img_keywords;
    //fill cap_array with sorted pids in current category 
    $result        = mysql_query("SELECT img_cap FROM gallery_imgs WHERE category_name='" . addslashes($cname) . "' ");
    $ct            = mysql_num_rows($result);
    while ($row = mysql_fetch_array($result)) {
        $row[0]      = trim($row[0]);
        $row[0]      = str_replace(" ", "-", $row[0]);
        $row[0]      = str_replace("'", "%27", $row[0]);
        $cap_array[] = trim($row[0]);
    }
    mysql_free_result($result);
    if (empty($nr)) {
        $result_final = "\t<tr><td>***No img found*******</td></tr>\n";
    } else {
        $category_name = $cname;
        $cname         = str_replace(" ", "-", $cname);
        $result_final  = "
            <div class=limagePage>
            <div class=llink><a href='gallery.php'>ALBUMS</a><span class=arrow>&gt;&gt</span><a href='gallery.php?cname=$cname'>$category_name</a></div>
             ";
        // display previous and next links if more than one img 
        if ($ct > 1) {
            $pcap = trim($pcap);
            $pcap = str_replace(" ", "-", $pcap);
            $pcap = str_replace("'", "%27", $pcap);
            $key  = array_search($pcap, $cap_array);
            $prev = $key - 1;
            if ($prev < 0)
                $prev = $ct - 1;
            $next = $key + 1;
            if ($next == $ct)
                $next = 0;
            $total_count = count($cap_array);
            $result_final .= "<div class='prevnext'>";
            $result_final .= "<span class='prev'><a href='gallery.php?cname=$cname&pcap=" . ($cap_array[$next]) . "'><img src='imgs/assets/left.png'  border='0' ></a></span>";
            $result_final .= "<span class='next'><a href='gallery.php?cname=$cname&pcap=" . ($cap_array[$prev]) . "'><img src='imgs/assets/right.png'  border='0' ></a></span>";
            $result_final .= "</div>";
        }
    }
    $cname = str_replace(" ", "-", $cname);
    $result_final .= "<div class=limage><table><tr><td><table class=image><tr>\n\t<td><a href='gallery.php?cname=$cname&pcap=" . ($cap_array[$next]) . "'><img src='" . $images_dir . "/" . $img_filename . "' border='0' alt='" . $img_keywords . "' /></a>
      <div class=cap>" . $img_cap . "</div> 
      <div class='excerpt'>" . $img_description . "</div> 
      </td>                    
      </tr></table></td></tr></table><div class=underline></div></div>
      <!-- .limagePage --></div>    ";
}
// Final Output
echo <<<__HTML_END

HTML

__HTML_END;

#1: Well first, let me address…

It’s uncommon to pass a full string on the URL. Normally you’d just pass… for example, the filename. Pass the index of the table so that the query can execute it (it’s possible to have the same caption for different pictures in the same category; so that shouldnt be an index of the table.)

#2: Mysql_
the Mysql_ library is being deprecated and removed from future versions of PHP; you will want to look at migrating to mysqli_ or PDO. [You already identified this yourself.]

#3: Queries.
Your queries have no ORDER BY clause, which means they are technically an uncertain order and the ‘next’ image in a gallery may be different each time. Suggest you implement some structuring here.

#4: Your search code
It’s not in the page you’re showing me. So… how does the search load an image?

#5: Rather than trying to make this old, clunky code work…
You’d get better results making your own, cleaner version, and really only steal the HTML structure. This code is very convoluted.

Thank you let me attach the whole search code…
The search code is

include('');
function html_escape($input, $encoding)
{
    return htmlentities($input, ENT_QUOTES, $encoding);
}
if (isset($_GET['form_id:search'])) {
    $images_dir = '';
    $q          = $_GET['q'];
    $sql        = mysqli_query($mysqli, "
SELECT

created_date
, gallery_description
, img_description
, img_cap
, img_filename
, category_name
, photo_keywords
FROM
gallery_imgs
WHERE
photo_keywords   like '%" . mysqli_real_escape_string($mysqli, $q) . "%'
OR 
img_cap like '%" . mysqli_real_escape_string($mysqli, $q) . "%'
");
    $num_rows   = mysqli_num_rows($sql);
    if ($num_rows > 0) {
        $results = "<h4>Search Results - </h4>
<span class=p1>Your search for <span class='searchText'>$q</span> returned <span class='searchNumber'>$num_rows</span> results </span>

<div class=searchresults><table>
<thead>
<tr>
<th class=p>Photo</th>
<th class=c>Caption</th> 

</tr>
</thead>";
        while ($rows = mysqli_fetch_assoc($sql)) {
            $rows['category_name'] = trim($rows['category_name']);
            $rows['img_cap'] = trim($rows['img_cap']);
            $rows['category_name'] = str_replace(" ", "-", $rows['category_name']);
            $rows['img_cap'] = str_replace(" ", "-", $rows['img_cap']);
            $parameters_search     = array(
                'cname' => $rows['category_name'],
                'pcap' => $rows['img_cap']
            );
            
            $results .= '

<tr>

<td><a href="' . html_escape('gallery.php?' . http_build_query($parameters_search), 'UTF-8') . '"><img src="' . $images_dir . '/tb_' . $rows['photo_filename'] . '" alt="' . htmlspecialchars($rows['img_cap']) . '"></a></td>
<td class=image-caption>' . htmlspecialchars($rows['img_cap']) . '</td>

</tr>
';
        }
        $results .= "</table></div>";
    } else {
        $results = "<span class='end'>Sorry, no results for <span class='searchText'>$q</span> were found !! </span>";
    }
}

Thank you for being patient with me. I am very new at this.

Hrm. So your search calls the gallery; but the gallery then overrides the resultset.

Well. That’s going to be a nasty thing to try and straighten out. To the degree of “I really would recommend starting from scratch because it’s going to get even more convoluted to try and de-spaghetti what you’re about to do”.

You could try sending the search text into the gallery page (as part of $parameters_search), and then tweak the gallery page code to say “If $searchtext exists, use THIS query instead of the normal one to find the photoset”.

Thank you Lion, I will try your suggestion. Yes a lot of people now are telling me to ditch the code. I am just trying to learn from this for now. Already started learning PHP from scratch, thank you for your help.

Feel free to bounce your ideas and code off of us here; as long as you’re trying to do the work and not just looking for a handout of a script, you’ll find many willing to help!

I will share the code here as it evolves. No I don’t want a code written for me. I would like to get the satisfaction of involving in the code writing process. Thanks for the pointers that you gave me and for your time.