user1504106
user1504106

Reputation: 3

Session issues with a PHP/MySQL search engine

PHP/MySQL newbie here.

I've created a basic search engine that queries a MySQL table containing a number of values. However, the search form has MULTIPLE search buttons in order to limit a search based on a single value type (in this case, by region or magnitude, since we're working with earthquakes)

The initial search and displaying of results goes off without a hitch, but when I try to go to another page of the results using the pagination links, it can't pull up the next set of results, and when I click in my browser (I'm using Firefox, but I'll test this in other browsers), the session has expired, so I've managed to narrow the problem down to there (unless I'm barking up the completely wrong tree here)

What's going wrong here, and how do I fix it?

I feel like the answer is very simple, but I'm just not seeing it. Here's the code for the results page (it was hacked together from multiple tutorials I found on the Internet, but I do understand what's happening within the code), and I added the var_dump($_SESSION) commands to see what variables were being passed in the session and will be removed once this problem is fixed.

<?php
include('db.php');  // include your code to connect to DB.
session_start();
var_dump($_SESSION);
if (mysql_real_escape_string($_POST['regbutton']) == submit||(!isset($_SESSION['submit1']))||!(isset($_SESSION['submit2']))){
$_SESSION['search']=mysql_real_escape_string($_POST['regbutton']);
$_SESSION['submit1']=mysql_real_escape_string($_POST['place']);
$_SESSION['submit2']=mysql_real_escape_string("empty");
$place =mysql_real_escape_string($_SESSION['submit1']);
$clicked=mysql_real_escape_string($_SESSION['search']);
var_dump($_SESSION);
}
elseif(mysql_real_escape_string($_POST['magbutton']) == submit|| (!isset($_SESSION['submit1']))||!(isset($_SESSION['submit2']))){
$_SESSION['search']=mysql_real_escape_string($_POST['magbutton']);
$_SESSION['submit1']=mysql_real_escape_string($_POST['mag1']);
$_SESSION['submit2']=mysql_real_escape_string($_POST['mag2']);
$mag1 = mysql_real_escape_string($_SESSION['submit1']);
$mag2 = mysql_real_escape_string($_SESSION['submit2']);
$clicked=mysql_real_escape_string($_SESSION['search']);
var_dump($_SESSION);
}
else{
var_dump($_SESSION);
echo "No records found. Session might be broken.";
exit;
} 
$tbl_name="quake";      //your table name
// How many adjacent pages should be shown on each side?
$adjacents = 3;
$query = "SELECT COUNT(*) as num FROM $tbl_name";
$result = mysql_query($query);
$total_pages = mysql_fetch_array($result);
$total_pages = $total_pages[num];

/* Setup vars for query. */
$targetpage = "resultz.php";    //your file name  (the name of this file)
$limit = 30;                                //how many items to show per page
$page = $_GET['page'];
if($page) 
    $start = ($page - 1) * $limit;          //first item to display on this page
else
    $start = 0;                             //if no page var is given, set start to 0

/* Get data. */
if (mysql_real_escape_string($_POST['regbutton']) == submit){
$query = "SELECT * FROM quake WHERE region LIKE '%of%, $place%' LIMIT $start, $limit";
}
elseif (mysql_real_escape_string($_POST['magbutton']) == submit){
if ($mag2 >= $mag1) {
$query = "SELECT * FROM quake WHERE magnitude BETWEEN '$mag1' and '$mag2' LIMIT $start, $limit";
}
else{
$query = "SELECT * FROM quake WHERE magnitude BETWEEN '$mag2' and '$mag1' LIMIT $start, $limit";
}
}
else{
echo "No records found.";
exit;
}

$result = mysql_query($query) or die(mysql_error());;

/* Setup page vars for display. */
if ($page == 0) $page = 1;          //if no page var is given, default to 1.
$prev = $page - 1;                 //previous page is page - 1
$next = $page + 1;              //next page is page + 1
$lastpage = ceil($total_pages/$limit);      //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1;                      //last page minus 1

/* 
    Now we apply our rules and draw the pagination object. 
    We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{   
    $pagination .= "<div class=\"pagination\">";
    //previous button
    if ($page > 1) 
        $pagination.= "<a href=\"$targetpage?page=$prev\"> previous</a>";
    else
        $pagination.= "<span class=\"disabled\"> previous</span>";  

    //pages 
    if ($lastpage < 7 + ($adjacents * 2))   //not enough pages to bother breaking it up
    {   
        for ($counter = 1; $counter <= $lastpage; $counter++)
        {
            if ($counter == $page)
                $pagination.= "<span class=\"current\">$counter</span>";
            else
                $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
        }
    }
    elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
    {
        //close to beginning; only hide later pages
        if($page < 1 + ($adjacents * 2))        
        {
            for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<span class=\"current\">$counter</span>";
                else
                    $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
            }
            $pagination.= "...";
            $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
            $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";       
        }
        //in middle; hide some front and some back
        elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
        {
            $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
            $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
            $pagination.= "...";
            for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<span class=\"current\">$counter</span>";
                else
                    $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
            }
            $pagination.= "...";
            $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
            $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";       
        }
        //close to end; only hide early pages
        else
        {
            $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
            $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
            $pagination.= "...";
            for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<span class=\"current\">$counter</span>";
                else
                    $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
            }
        }
    }

    //next button
    if ($page < $counter - 1) 
        $pagination.= "<a href=\"$targetpage?page=$next\">next </a>";
    else
        $pagination.= "<span class=\"disabled\">next </span>";
    $pagination.= "</div>\n";       
}

?>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<link rel="stylesheet" media="print" type="text/css" href="print.css" />
<title>Recent Earthquakes</title>
</head>
<div id="header">
QUAKE SEARCH 
</div>
<div id="header2">
Search the latest quakes
</div>
<table border=1>
<thead>
<td>Source</td>
<td>EqID</td>
<td>Version</td>
<td>Date/Time</td>
<td>Latitude</td>
<td>Longitude</td>
<td>Magnitude</td>
<td>Depth</td>
<td>NST</td>
<td>Region</td>
</thead>
<?php
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
?>
<?=$pagination?>

And here is the search form:

<?php
session_start();
include ('db.php');
?>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<link rel="stylesheet" media="print" type="text/css" href="print.css" />
<title>Recent Earthquakes</title>
</head>
<div id="header">
QUAKE SEARCH 
</div>
<div id="header2">
Search the latest quakes
</div>
<div id="search">
<form name="magsearch" action="resultz.php" method="post">
<label>Search by Magnitude:</label>
<select name="mag1">
<option>1.0</option>
<option>2.0</option>
<option>3.0</option>
<option>4.0</option>
<option>5.0</option>
<option>6.0</option>
<option>7.0</option>
<option>8.0</option>
<option>9.0</option>
<option>10.0</option>
</select>
<select name="mag2">
<option value=1>1.0</option>
<option value=2>2.0</option>
<option value=3>3.0</option>
<option value=4>4.0</option>
<option value=5>5.0</option>
<option value=6>6.0</option>
<option value=7>7.0</option>
<option value=8>8.0</option>
<option value=9>9.0</option>
<option>10.0</option>
</select>
<input name="magbutton" type="submit" value="submit" />
<input type="hidden" name="content" value="search">
</form>  
<form name ="regsearch" action="resultz.php" method="post">
<label>Search by Region:</label>
<input name="place" type="text" size="14" />
<input name="regbutton" type="submit" value="submit" />
<input type="hidden" name="content" value="search">
</form>  
</div>

Upvotes: 0

Views: 647

Answers (1)

Marc B
Marc B

Reputation: 360662

What is the point of

if (mysql_real_escape_string($_POST['regbutton']) == submit||

You don't need to escape form data if you're not using it in an SQL operation - you're just going a comparison in PHP here, with no database in site for this particular line of code. As well, you're comparing your escaped form value against an undefined constant - note the lack of quotes around submit. PHP will politely treat that as an unquoted string, but will issue a warning - given you've not mentioned getting any warnings, you're probably working with display_errors off - meaning you're not going to see ANY problem reports from your code.

These errors are repeated throughout your code, so don't just fix this one line - fix the entire script.

Change that line to

if ($_POST['regbuttn'] == 'submit') || etc...

and then go read the PHP manual on how to enable display_errors. With this off, you're working in the dark and shooting yourself in the foot, repeatedly.

Plus... don't use the presence of a form field to determine if a POST has occured. It's unreliable. Use

if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }

instead, which is 100% reliable.

Upvotes: 1

Related Questions