Variable is empty, yet thinks it's isset - why?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

Code: Select all

<?php

$search = isset($_GET['search']) ? $_GET['search'] : null;
if ($search == "")
{
$search = NULL;
}

if (isset($search))
{
echo "yes";
}
This is the real basics of the code, but reveals the issue. If I post "/index.php?page=search&category=all&search=" to the page using _GET, the isset($search) makes it products pages and pages of products.

Surely the code at the top that asks if $search is empty, then set i$search to be a NULL value.
Why won't it?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Variable is empty, yet thinks it's isset - why?

Post by requinix »

You seem to be confusing isset() with empty().
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Variable is empty, yet thinks it's isset - why?

Post by Celauran »

[text]❯ php -a
Interactive shell

php > $search = '';
php > var_dump(isset($search));
bool(true)
php > var_dump(empty($search));
bool(true)
php >[/text]
Don't use isset to check for empty.
simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

I'm not. I'm using isset to check if the variable is set. But then I realised the form can be posted without anything in it.
So then I thought if it's posted but is empty, I can set $search to be NULL - is that !isset ?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Variable is empty, yet thinks it's isset - why?

Post by Celauran »

!isset simply negates isset. If your $_GET['isset'] is an empty string, you're then setting it to null, which should fail the second isset test and therefore not echo 'yes'. Is this not what you're intending?
simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

I'm saying, if an empty field named search is posted via a GET to the search page, I want it to NOT run a search.
I have the code that if (!isset) then do something else. But it keeps telling me something is in there, even with this:

Code: Select all

if (isset($search) && !empty ($search))
{

}
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Variable is empty, yet thinks it's isset - why?

Post by Celauran »

That doesn't make sense. isset checks if the variable exists and is not null. empty checks if the variable is an empty string or an empty array. &search= would fail the second condition. If you have explicitly set it to null prior, then the first condition would fail. There must be something we're not seeing.
simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

A form is submitted, but nothing is put in &search=.
On the results page, it is running the query.
$search = isset($_GET['search']) ? $_GET['search'] : null;
I guess because this is in the code, even tho nothing is in there, it's thinking it's set.
But I am then saying at the top, if $search == "", then set $search = NULL.
But it still pulls in everything.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Variable is empty, yet thinks it's isset - why?

Post by Celauran »

simonmlewis wrote:A form is submitted, but nothing is put in &search=.
On the results page, it is running the query.
$search = isset($_GET['search']) ? $_GET['search'] : null;
I guess because this is in the code, even tho nothing is in there, it's thinking it's set.
But I am then saying at the top, if $search == "", then set $search = NULL.
But it still pulls in everything.
It doesn't think it's set, it is set. It just happens to be set to an empty string. You could change that initial ternary to check if it's set and not empty, but I would expect the check against empty string to have caught that anyhow, which is why I suspect the culprit may lie elsewhere in the code.
simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

I checked to see if I have it in a session, but it isn't. the only session is elsewhere in the page for the filters, as each page number has the search criteria in the URL.
Why can I not just "unset" it, if the variable is empty.
Though if the various is empty, surely I should use that instead of isset.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

If I ask:

Code: Select all

$search = isset($_GET['search']) ? $_GET['search'] : null;
if (empty($search))
{
echo "empty";
}
It's echoing "empty".

But if I ask:

Code: Select all

if (!empty($search))
further down, it does what is in that query.

Bizarre.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Variable is empty, yet thinks it's isset - why?

Post by requinix »

What's the rest of the code between those two points?
simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

This is all of it.
Although a lot of to be stripped out, as if there is no search to be run, it will just show a list of categories and subs.

As of now, it runs a search even if $search has nothing in it.

Code: Select all

<script>
function toggleDiv(divId) {
   $("#"+divId).toggle();
}

$(document).click(function() {
    
});
$("#txthint").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

</script>
<?php
$search = isset($_GET['search']) ? $_GET['search'] : null;
if (empty($search))
{
echo "empty";
}
$category = isset($_GET['category']) ? $_GET['category'] : null;
$powered = isset($_GET['powered']) ? $_GET['powered'] : null;
$colour = isset($_GET['colour']) ? $_GET['colour'] : null;
$hopup = isset($_GET['hopup']) ? $_GET['hopup'] : null;
$stock = isset($_GET['stock']) ? $_GET['stock'] : null;
$manufacturer = isset($_GET['manufacturer']) ? $_GET['manufacturer'] : null;
$reset = isset($_GET['reset']) ? $_GET['reset'] : null;
$categorysearch = str_replace("+", " ", $category);
$detect = new Mobile_Detect;
if (isset($_SERVER['HTTP_REFERER']))
{
$prevurl = $_SERVER['HTTP_REFERER'];
if(!preg_match('/search/i', $prevurl))
{
  $reset = "yes";
}
}


if (isset($reset))
{
unset($_SESSION['powered']);
unset($_SESSION['colour']);
unset($_SESSION['hopup']);
unset($_SESSION['manufacturer']);
unset($_SESSION['stock']);
$powered = "";
$colour = "";
$hopup = "";
$manufacturer = "";
$stock = "";
}

// by default we show first page
$pageNum = 1;
 
// if $_GET['pagenum'] defined, use it as page number
if(isset($_GET['pagenum']))
{
    $pageNum = $_GET['pagenum'];
}

if ( $detect->isMobile() && !$detect->isTablet() ) {
	  // how many rows to show per page
$rowsPerPage = 12;
}
else
{
	  // how many rows to show per page
$rowsPerPage = 32;
}

$offset = ($pageNum - 1) * $rowsPerPage;	
$sort = isset($_GET['sort']) ? $_GET['sort'] : null;
$powered = isset($_GET['powered']) ? $_GET['powered'] : null;
$reset = isset($_GET['reset']) ? $_GET['reset'] : null;

if (isset($reset))
{
unset($_SESSION['powered']);
unset($_SESSION['colour']);
unset($_SESSION['hopup']);
unset($_SESSION['manufacturer']);
$powered = "";
$colour = "";
$hopup = "";
$manufacturer = "";
}

if(isset($_GET['cname']))
{
    $cname = $_GET['cname'];
    $cnamesort = $_GET['cname'];
    $cname = str_replace("-", " ", $cname);
    $_SESSION['cname']=$cname;
    $_SESSION['cnamesort']=$cnamesort;
} elseif (isset($_SESSION['cname'])) {
    $cname=$_SESSION['cname'];
    $cnamesort=$_SESSION['cnamesort'];
}

if(isset($_GET['sort']))
{
    $sort = $_GET['sort'];
    $_SESSION['sort']=$sort;
} elseif (isset($_SESSION['sort'])) {
    $sort=$_SESSION['sort'];
}

if (!isset($sort)) 
{ 
$sortby = "title ASC";
$sort = "titleaz";
}

if(isset($_GET['powered']))
{
    $powered = $_GET['powered'];
    if ($powered == "showall") { $powered = "";}
    $_SESSION['powered']=$powered;
} elseif (isset($_SESSION['powered'])) {
    $powered=$_SESSION['powered'];
}

if(isset($_GET['colour']))
{
    $colour = $_GET['colour'];
    if ($colour == "showall") { $colour = NULL;}
    $_SESSION['colour']=$colour;
} elseif (isset($_SESSION['colour'])) {
    $colour=$_SESSION['colour'];
}

if(isset($_GET['hopup']))
{
    $hopup = $_GET['hopup'];
    if ($hopup == "showall") { $hopup = "";}
    $_SESSION['hopup']=$hopup;
} elseif (isset($_SESSION['hopup'])) {
    $hopup=$_SESSION['hopup'];
}


if(isset($_GET['manufacturer']))
{
    $manufacturer = $_GET['manufacturer'];
    if ($manufacturer == "showall") { $manufacturer = "";}
    $_SESSION['manufacturer']=$manufacturer;
} elseif (isset($_SESSION['manufacturer'])) {
    $manufacturer=$_SESSION['manufacturer'];
}

if (!isset($manufacturer)) 
{ 
$manufacturer = "";
}

if(isset($_GET['stock']))
{
    $stock = $_GET['stock'];
    if ($stock == "showall") { $stock = "";}
    else { $stock == "in stock";}
    $_SESSION['stock']=$stock;
} elseif (isset($_SESSION['stock'])) {
    $stock=$_SESSION['stock'];
}

if (!isset($stock)) 
{ 
$stock = "";
}

if (isset($sort))
{
  if ($sort == "titleaz") { $sortby = "title ASC";}
  if ($sort == "titleza") { $sortby = "title DESC";}
  if ($sort == "pricelow") { $sortby = "price ASC";}
  if ($sort == "pricehigh") { $sortby = "price DESC";}
}

echo "<div class='head'><h1>Search: ";?><?= htmlspecialchars($search); ?><?php echo " <i class='fa fa-search' aria-hidden='true' style='color: #ff5500'></i></h1>";
if (isset($category) && $category <> "all") { echo "<h2>";?><?= htmlspecialchars($categorysearch); ?><?php echo "</h2>";}
echo "</div>
<div class='home-search'>
<div class='home-search-inner'>
<form method='GET' action='/index.php'>
<input type='hidden' name='page' value='search'>
<div class='home-search-icon'><i class='fa fa-search' aria-hidden='true'></i></div>
<div class='home-search-input'> <input type='text' name='search' autocomplete='off' placeholder='Search the site'";
if (isset($search)) { echo " value='";
?><?= htmlspecialchars($search); ?><?php
echo "'";}
echo ">
<div id='txthint'></div>
</div>
<div class='home-search-cat'><select name='category'>
<option value='all'>All Categories</option>";

  $query = "SELECT DISTINCT catname FROM products WHERE pause = 'off' ORDER BY catname";
  $result = $pdo->query($query);
  while ($row = $result->fetch(PDO::FETCH_OBJ)) 
      {
      
      echo "<option value='$row->catname'";
      if (isset($categorysearch)) 
      {
      if ($row->catname == $categorysearch) { echo " selected='selected'";}
      }
      echo ">$row->catname</option>";
      }

echo "</select></div>
<div class='home-search-submit'><input type='submit' value='search'></div>
</form>
<div style='clear: both'></div>
</div>";

if (!empty($search))
{

			echo "<div class='category-sort' id='menu'>
			<div class='category-sort-link'><a href='#'><i class='fa fa-sort' aria-hidden='true'></i> Sorted by";
			if (isset($sort)) { 
      if ($sortby == "title ASC") { echo ": Title A-Z";}
      if ($sortby == "title DESC") { echo ": Title Z-A";}
      if ($sortby == "price ASC") { echo ": Price Low-High";}
			if ($sortby == "price DESC") { echo ": Price High-Low";}
			}
			echo "</a>
			 <div class='category-sort-dropdown'>
 <a href='/index.php?page=search&search=$search&category=$category&sort=titleaz'>";
 if ($sort == "titleaz") { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "Title A-Z</a>
<a href='/index.php?page=search&search=$search&category=$category&sort=titleza'>";
 if ($sort == "titleza") { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "Title Z-A</a>
<a href='/index.php?page=search&search=$search&category=$category&sort=pricelow'>";
 if ($sort == "pricelow") { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "Price Low-High</a>
<a href='/index.php?page=search&search=$search&category=$category&sort=pricehigh'>";
 if ($sort == "pricehigh") { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "Price High-Low</a>
</div>
</div>

<div class='category-sort-link'";
if (isset($powered) && $powered <> '') { echo " style='background-color: #ff5500'";}
echo "><a href='#'><i class='fa fa-cog' aria-hidden='true'></i> Powered by";
			if (isset($powered)) { echo " $powered";}
			echo "</a>
			 <div class='category-sort-dropdown'>";
			 
			$querys = "SELECT DISTINCT powertype FROM products WHERE powertype <> '' ORDER BY powertype";
$results = $pdo->query($querys);
while ($rows = $results->fetch(PDO::FETCH_OBJ)) 
{ 			 
	echo "<a href='/index.php?page=search&search=$search&category=$category&powered=$rows->powertype'>";
 if ($powered == $rows->powertype) { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "$rows->powertype</a>";
 }
echo "<a href='/index.php?page=search&search=$search&category=$category&powered=showall'>Show all</a></div>
</div>


<div class='category-sort-link'";
if (isset($colour) && $colour <> '') { echo " style='background-color: #ff5500'";}
echo "><a href='#'><i class='fa fa-paint-brush' aria-hidden='true'></i> colour";
			if (isset($colour)) { echo " $colour";}
			echo "</a>
			 <div class='category-sort-dropdown'>";
			 
			$querys = "SELECT DISTINCT colour FROM products  WHERE colour <> '' ORDER BY colour";
$results = $pdo->query($querys);
while ($rows = $results->fetch(PDO::FETCH_OBJ)) 
{ 			 
	echo "<a href='/index.php?page=search&search=$search&category=$category&colour=$rows->colour'>";
 if ($colour == $rows->colour) { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "$rows->colour</a>";
 }
echo "<a href='/index.php?page=search&search=$search&category=$category&colour=showall'>Show all</a></div>
</div>


<div class='category-sort-link'";
if (isset($hopup) && $hopup <> '') { echo " style='background-color: #ff5500'";}
echo "><a href='#'><i class='fa fa-spinner' aria-hidden='true'></i> hopup";
			if (isset($hopup)) { echo " $hopup";}
			echo "</a>
			 <div class='category-sort-dropdown'>";
			 
			$querys = "SELECT DISTINCT hopup FROM products  WHERE hopup <> '' ORDER BY hopup";
$results = $pdo->query($querys);
while ($rows = $results->fetch(PDO::FETCH_OBJ)) 
{ 			 
	echo "<a href='/index.php?page=search&search=$search&category=$category&hopup=$rows->hopup'>";
 if ($hopup == $rows->hopup) { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "$rows->hopup</a>";
 }
echo "<a href='/index.php?page=search&search=$search&category=$category&hopup=showall'>Show all</a></div>
</div>



<div class='category-sort-link'";
if (isset($manufacturer) && $manufacturer <> '') { echo " style='background-color: #ff5500'";}
echo "><a href='#'><i class='fa fa-user' aria-hidden='true'></i> manufacturer";
			if (isset($manufacturer)) { echo " $manufacturer";}
			echo "</a>
			 <div class='category-sort-dropdown'>";
			 
			$querys = "SELECT DISTINCT manufacturer FROM products  WHERE manufacturer <> '' ORDER BY manufacturer";
$results = $pdo->query($querys);
while ($rows = $results->fetch(PDO::FETCH_OBJ)) 
{ 			 
	echo "<a href='/index.php?page=search&search=$search&category=$category&manufacturer=$rows->manufacturer'>";
 if ($manufacturer == $rows->manufacturer) { echo "<i class='fa fa-chevron-right' aria-hidden='true'></i> ";}
 echo "$rows->manufacturer</a>";
 }
echo "<a href='/index.php?page=search&search=$search&category=$category&manufacturer=showall'>Show all</a></div>
</div>

<div class='category-sort-link'";
if (isset($stock) && $stock <> '') { echo " style='background-color: #ff5500'";}
echo "><a href='#'><label><input type='checkbox' name='stock' value='in' ";
if (!isset($stock) || $stock == '')
{
 echo "onclick='window.location.assign(\"/index.php?page=search&search=$search&category=$category&stock=in\")'";
}
else
{ 
  echo "onclick='window.location.assign(\"/index.php?page=search&search=$search&category=$category&stock=showall\")'";
}
if ($stock == "in") { echo " checked='checked'";}
echo "> in stock</label></a></div>



<div class='category-sort-link'><a href='/index.php?page=search&search=$search&category=$category&reset=all'><i class='fa fa-eraser' aria-hidden='true'></i> Reset all</a></div>
</div>
<div style='clear: both'></div>";
}

echo "</div>";

if (isset($category))
{
  if ($category == "all") 
  {
  $query = "SELECT * FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = '' DESC, $sortby, title LIMIT $offset, $rowsPerPage;";
  $result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
  }
  else
  {
  $category = str_replace("+", " ", $category); 
  $query = "SELECT * FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND catname =:category AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = 'out of stock' DESC, $sortby,  title LIMIT $offset, $rowsPerPage;";
  $result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':category' => $category, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
  }
}

$num_rows = $result->rowCount();
$count = 0;
$todaydate = date('Y-m-d');
echo "<div class='thumbs-container'>";
while ($row = $result->fetch(PDO::FETCH_OBJ)) 
      { 
        $count ++;
      $todaydate = date('Y-m-d');
      $newdate = strtotime("$todaydate");
      $datebackinstock = strtotime("$row->datebackinstock");
      $i=30;
      $checkBackinstock = strtotime(date("Y-m-d", strtotime($row->datebackinstock)) . " +".$i."days");

      if ($checkBackinstock >= $newdate) { $backinstock = "enable";}
            
      $titlereplace = str_replace(" ", "-", $row->title);
      $categreplace = str_replace(" ", "-", $row->catname);
      $subcategreplace = str_replace(" ", "-", $row->subname);  
      echo "<div class='thumbs-tile'><a href='/product/$categreplace/$subcategreplace/$row->id/$titlereplace'>
      <div class='thumbs-tile-colored'>
      <div class='thumbs-tile-colored-inner'>
      ";
  
  if($row->preorder == "yes" && isset($row->preorderdate))
    {
    if ($row->preorderdate > $todaydate) 
      { 
      $preorderdateyear = date( 'Y', strtotime($row->preorderdate));
      $preorderdatemonth = date( 'F', strtotime($row->preorderdate));
echo "<div class='thumb-tile-preorder'><i class='fa fa-clock-o'></i> DUE IN $preorderdatemonth $preorderdateyear</div>";
      }
    }
  
    if(isset($backinstock) && $row->rcstock == "in stock")
    {
    if ($backinstock == "enable") 
      { 
      echo "<div class='thumb-tile-backinstock'><i class='fa fa-check'></i> BACK IN STOCK</div>";
      }
    }
    

  if(isset($row->pricedropenable))
    {
    if ($row->pricedropenable == "yes") 
      { 
echo "<div class='thumb-tile-pricedrop'><i class='fa fa-caret-down'></i>&nbsp; PRICE DROP</div>";
      }
    }
     echo "</div></div>";  
    if (isset($row->bundleroman1) && $row->bundleroman1 != '')
{
if (isset($row->photoprimary) && $row->photoprimary != '')
{
$image = $row->photoprimary;
$srcset = getSrcSet($image, 'thumbnails');
echo "<img src='/images/productphotos/$image' srcset='{$srcset}' alt='$row->title'>";
}
else
{
echo "<img src='/images/blank_bundle.jpg'   alt='no image available' />";
}
}
else
{
if ($row->photoprimary == "" || $row->photoprimary == NULL)
        {
        echo "<img src='/images/blank.jpg'>";
        }
        else
        {
$image = $row->photoprimary;
$srcset = getSrcSet($image, 'thumbnails');
echo "<img src='/images/productphotos/$image' srcset='{$srcset}' alt='$row->title'>";
        }
        }
        
      echo "<div class='thumbs-tile-overlay'>
      <div class='thumbs-tile-overlay-inner'>
      <div class='thumbs-tile-title'>$row->title</div>
      
     <div class='thumbs-tile-price'>
     
     
     
     <div class='thumbs-tile-stock'>";
      
      if ($row->preorder == "yes") { echo "pre-order only";}
else if ($row->comingsoon == "yes") { echo "coming soon";}
else if ($row->bundleroman1 != NULL)
    {  

   $query1   = "SELECT rcstock FROM products WHERE romancode = :bundleroman1 AND rcstock = 'out of stock'";
	$result1  = $pdo->prepare($query1);
  $result1->execute(array(':bundleroman1' => $row->bundleroman1));
  $num_rows1 = $result1->rowCount();
    if ($num_rows1 != 0) 
      {
      $bundlestock1 = "sold";
      }
      else { $bundlestock1 = NULL; }
      
      
      
	$query2   = "SELECT rcstock FROM products WHERE romancode = :bundleroman2 AND rcstock = 'out of stock'";
	$result2  = $pdo->prepare($query2);
  $result2->execute(array(':bundleroman2' => $row->bundleroman2));
  $num_rows2 = $result2->rowCount();
    if ($num_rows2 != 0) 
      {
      $bundlestock2 = "sold";
      }
      else { $bundlestock2 = NULL; }
      
      
      
      	$query3   = "SELECT rcstock FROM products WHERE romancode = :bundleroman3 AND rcstock = 'out of stock'";
	$result3  = $pdo->prepare($query3);
    $result3->execute(array(':bundleroman3' => $row->bundleroman3));
  $num_rows3 = $result3->rowCount();
    if ($num_rows3 != 0) 
      {
      $bundlestock3 = "sold";
      }
      else { $bundlestock3 = NULL; }
      
      
      
    	$query4   = "SELECT rcstock FROM products WHERE romancode = :bundleroman4 AND rcstock = 'out of stock'";
	$result4  = $pdo->prepare($query4);
  $result4->execute(array(':bundleroman4' => $row->bundleroman4));
  $num_rows4 = $result4->rowCount();
    if ($num_rows4 != 0) 
      {
      $bundlestock4 = "sold";
      }
      else { $bundlestock4 = NULL; }
    	$query5   = "SELECT rcstock FROM products WHERE romancode = :bundleroman5 AND rcstock = 'out of stock'";
	$result5  = $pdo->prepare($query5);
  $result5->execute(array(':bundleroman5' => $row->bundleroman5));
  $num_rows5 = $result5->rowCount();
    if ($num_rows5 != 0) 
      {
      $bundlestock5 = "sold";
      }
      else { $bundlestock5 = NULL; }
      
    if ($bundlestock1 == "sold" || $bundlestock2 == "sold" || $bundlestock3 == "sold" || $bundlestock4 == "sold" || $bundlestock5 == "sold")
    {
    echo "out of stock";
    $bundlestock1 = null;
    $bundlestock2 = null;
    $bundlestock3 = null;
    $bundlestock4 = null;
    $bundlestock5 = null;
    }
    else
    {
    echo "in stock";
    }
    }
else
{ 
echo "$row->rcstock";
}

echo "</div>";
      
      if ($row->comingsoon != "yes")
  {    
    if ($row->pricedropenable == "yes") 
      { 
      echo "<span class='fontred'><i class='fa fa-caret-down'></i>&nbsp;</span> Only &euro;";
      printf ("%.2f", $row->price);
      echo "<div class='thumbs-tile-was'> Was <s>&euro;";
      printf ("%.2f", $row->pricedrop);
      echo "</s></div>";
      }
    else 
    {	
      echo "Only &euro;";
      printf ("%.2f", $row->price);
    }
  }
  else
  {
  echo "Price n/a";
  }
			
      echo "</div></div>
      </div></a>
      </div>";
            // if not on a mobile, ensure a clear line after ever four items, incase of dodgy image heights
      if ( $detect->isMobile() && !$detect->isTablet() ) {
}
else
{
 if (($count % 4) == 0)
      {
      echo "<div style='clear:both'></div>";
      }
}
$pricedrop = NULL;
$backinstock = NULL;
if (($count % 2) == 0)
      {
      echo "<div class='thumbs-tile-mobile-clrrow'>&nbsp;</div>";
      }
    }
     echo "<div style='clear:both'></div></div>";
     if ($num_rows == 0)
     {
    echo "<div class='search-welcome'><h2>Nothing found....</h2>
     Sorry we couldn't find a result for you.<br/>Please try again.";
     
if (isset($powered)) { echo "<div class='thumbnails-filterwarning-filter'><i class='fa fa-cog' aria-hidden='true'></i> Powered by $powered <a href='/index.php?page=search&search=$search&category=$category&powered=showall' style='color: #ffffff'><i class='fa fa-times' aria-hidden='true'></i></a></div>";}
if (isset($colour)) { echo "<div class='thumbnails-filterwarning-filter'><i class='fa fa-paint-brush' aria-hidden='true'></i> Colour: $colour <a href='/index.php?page=search&search=$search&category=$category&colour=showall' style='color: #ffffff'><i class='fa fa-times' aria-hidden='true'></i></a></div>";}
if (isset($hopup) && $hopup <> '') { echo "<div class='thumbnails-filterwarning-filter'><i class='fa fa-angle-up' aria-hidden='true'></i> Hopup: $hopup <a href='/index.php?page=search&search=$search&category=$category&hopup=showall' style='color: #ffffff'><i class='fa fa-times' aria-hidden='true'></i></a></div>";}
if (isset($manufacturer) && $manufacturer <> '') { echo "<div class='thumbnails-filterwarning-filter'><i class='fa fa-user' aria-hidden='true'></i> $manufacturer <a href='/index.php?page=search&search=$search&category=$category&manufacturer=showall' style='color: #ffffff'><i class='fa fa-times' aria-hidden='true'></i></a></div>";}

if (isset($stock) && $stock <> '') { echo "<div class='thumbnails-filterwarning-filter'><i class='fa fa-check-square' aria-hidden='true'></i> $stock stock <a href='/index.php?page=search&search=$search&category=$category&stock=showall' style='color: #ffffff'><i class='fa fa-times' aria-hidden='true'></i></a></div>";}

     echo "</div>";
     }
     if (!isset($search) || empty($search))
     {
    echo "<div class='head'><h2>All departments</h1></div><div class='width-narrow'>";

$count = 0;
$query = ("SELECT catname, catid FROM products WHERE pause = 'off'  GROUP BY catid ORDER BY catname");
$result = $pdo->query($query);
$num_rows = $result->rowCount();
while ($row = $result->fetch(PDO::FETCH_OBJ)) 
      {
      $count ++;
      $categ = "$row->catname"; 
      $findcateg ="/ /"; 
      $replacecateg ="-"; 
      $categreplace = preg_replace ($findcateg, $replacecateg, $categ); 
 
      echo "<div class='alldepts'>
      <div class='alldepts_catname'><h2";
      if ($count == "1") { echo " style='border-top: 0px;'";}
      echo "><a href='/categ/$categreplace'>$row->catname</a></h2></div>";
      
      $query2 = ("SELECT subname, subid FROM products WHERE pause = 'off' AND catid =:catid GROUP BY subid ORDER BY subname");
$result2 = $pdo->prepare($query2);
$result2->execute(array(':catid' => $row->catid));
while ($row2 = $result2->fetch(PDO::FETCH_OBJ)) 
      {
      
      $subcateg = "$row2->subname"; 
      $findsubcateg ="/ /"; 
      $replacesubcateg ="-"; 
      $subcategreplace = preg_replace ($findsubcateg, $replacesubcateg, $subcateg); 
      echo "<div class='alldepts_subname'><a href='/subcateg/$categreplace/$subcategreplace/'>$row2->subname</a></div>";
      }
      echo "</div>";

}
echo "<div style='clear: both'></div></div>";
     
     }
     echo "<div style='clear:both'></div>";
     if (isset($search) && $num_rows > 0)
     {
     echo "<Br/>";
     }

$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  
  if ($category == "all") 
  {
	$query = "SELECT count(id) AS numrows FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = 'out of stock' DESC, $sortby";
$result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
	}
	else
	{
	$query   = "SELECT count(id) AS numrows FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND catname =:category AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = 'out of stock' DESC, $sortby";
	$result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':category' => $category, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
	}
  $numrows = $result->fetchColumn();
$maxPage = ceil($numrows/$rowsPerPage);

$category = str_replace(" ", "+", $category);

// print the link to access each page
$self = $_SERVER['PHP_SELF'];
$nav  = '';
 
for($page = 1; $page <= $maxPage; $page++)
{
   if ($page == $pageNum)
   {
      $nav .= " <div class='pagelinkactive'>$page</div> "; // no need to create a link to current page
   }
   else
   {
      $nav .= " <a href=\"/index.php?page=search&search=$search&category=$category&pagenum=$page\" class='pagelink'>$page</a>";
   }
}
 
// creating previous and next link
// plus the link to go straight to
// the first and last page
 
if ($pageNum > 1)
{
   $page  = $pageNum - 1;
   $prev  = " <a href=\"/index.php?page=search&search=$search&category=$category&pagenum=$page\" class='pagelink'>Prev</a> ";
 
   $first = " <a href=\"/index.php?page=search&search=$search&category=$category\" class='pagelink'>First Page</a>";
}
else
{
   $prev  = '&nbsp;'; // we're on page one, don't print previous link
   $first = '&nbsp;'; // nor the first page link
}
 
if ($pageNum < $maxPage)
{
   $page = $pageNum + 1;
   $next = " <a href=\"/index.php?page=search&search=$search&category=$category&pagenum=$page\" class='pagelink'>Next</a>";
 
   $last = " <a href=\"/index.php?page=search&search=$search&category=$category&pagenum=$maxPage\" class='pagelink'>Last Page</a>";
}
else
{
   $next = '&nbsp;'; // we're on the last page, don't print next link
   $last = '&nbsp;'; // nor the last page link
}
if (isset($search))
{
// print the navigation link
echo "<div class='navpages'>" . $first . $prev . $nav . $next . $last . "</div>";    
}
			?>

<?php
if ( $detect->isMobile() && !$detect->isTablet() ) {
}
else
{
echo "<script>
// This really belongs in a separate JS file, not embedded alongside PHP or HTML
$(document).ready(function() {
$('.home-search-input input').on('keyup', function(event) {
  var search_string = $(this).val();

  // Don't fire on very short strings
  if (search_string.length > 2) {
    var category = $('.home-search-cat select').val();
    $.ajax({
                url: '/ajax-search.php?search=' + search_string + '&category=' + category,
                method: 'GET'
            }).done(function(response) {
                $('#txthint').html(response);
            });
  }
});

$('.home-search-cat select').change(function(event) {
	var category = $(this).val();
  var search_string = $('.home-search-input input').val();
    $.ajax({
                url: '/ajax-search.php?search=' + search_string + '&category=' + category,
                method: 'GET'
            }).done(function(response) {
                $('#txthint').html(response);
            });
});
});
</script>";
}
?>
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Variable is empty, yet thinks it's isset - why?

Post by requinix »

If by "runs a search" you mean it does database queries then yes, it sure will:

Code: Select all

if (isset($category))
{
  if ($category == "all") 
  {
  $query = "SELECT * FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = '' DESC, $sortby, title LIMIT $offset, $rowsPerPage;";
  $result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
  }
  else
  {
  $category = str_replace("+", " ", $category); 
  $query = "SELECT * FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND catname =:category AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = 'out of stock' DESC, $sortby,  title LIMIT $offset, $rowsPerPage;";
  $result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':category' => $category, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
  }
}
Nothing in there says it should only happen if $search has a value.

You might be specifically thinking of

Code: Select all

  if ($category == "all") 
  {
        $query = "SELECT count(id) AS numrows FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = 'out of stock' DESC, $sortby";
$result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
        }
        else
        {
        $query   = "SELECT count(id) AS numrows FROM products WHERE (title LIKE :search OR description LIKE :search OR metakeywords LIKE :search OR romancode LIKE :search OR MATCH(title) AGAINST (:searchmatch)) AND pause <> 'on' AND catname =:category AND powertype LIKE :powered AND colour LIKE :colour AND hopup LIKE :hopup AND manufacturer LIKE :manufacturer AND rcstock LIKE :stock ORDER BY rcstock = 'in stock' DESC,  rcstock = 'out of stock' DESC, $sortby";
        $result = $pdo->prepare($query);
  $result->execute(array(':search' => "%{$search}%", ':searchmatch' => $search, ':category' => $category, ':powered' => "%{$powered}%", ':colour' => "%{$colour}%", ':hopup' => "%{$hopup}%", ':manufacturer' => "%{$manufacturer}%", ':stock' => "%{$stock}%"));
        }
The incorrect indentation level may be misleading you into thinking it's inside one of the if blocks from earlier. It is not.

Learn to indent your code because it can save you hours of time getting frustrated at PHP when the problem is on your end.
simonmlewis
DevNet Master
Posts: 4434
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Variable is empty, yet thinks it's isset - why?

Post by simonmlewis »

Line 219:
if (!empty($search))
{
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply