-2

I have a form that I need to submit to a search page and I want the search script to NOT return records where "active" = 0. (active can only be 1 or 0). The problem is that the active variable which I am passing in the hidden input below is either not the correct way to pass this variable, or else the search script is not correctly processing the active variable on the search page. Can anyone see what the active variable is being ignored when returning my results?

//The search form


<form name="search" method="get" action="http://example.com/searchb/">
 <p>&nbsp;</p>
    Category:
    <select name="category">
        <?php foreach($categories_list as $category) : ?>
            <option><?php echo $category; ?></option>
        <?php endforeach; ?>
    </select>


<p>&nbsp;</p>
    Keywords:
    <input type="text" name="keywords">
<input type="hidden" name="active" value="0">
<input type="submit"/>
</form>




//some relevant code from the search.php script:

$category = $_GET['category'];
$active = $_GET['active'];

try {


$where_sql .= " AND s.category = '".$category."'";

if(empty($active) == false) {
    $where_sql .= " AND s.active = '".$active."'";
}

// Find out how many items are in the table
$total = $dbh->query("SELECT COUNT(*) FROM searching s WHERE 1  
{$where_sql}")->fetchColumn();
JA4677
  • 521
  • 3
  • 7
  • 12

1 Answers1

0

0 is empty, http://php.net/manual/en/function.empty.php. Try...

if(isset($active) && is_numeric($active)) {
    $where_sql .= " AND s.active = '".$active."'";
}

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

Also note this code opens you to SQL injections you should use parameterized queries.

Another approach would be adding an else. If it isn't 1 make it search for active = 0, not sure if that is the correct behavior though.

SQL injection prevention links:

How can I prevent SQL injection in PHP?
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29

Community
  • 1
  • 1
chris85
  • 23,846
  • 7
  • 34
  • 51
  • Genius. Thanks! Do you think I need to do this for another search where active = 1 too? – JA4677 Jul 15 '15 at 03:27
  • `1` is not empty so `1` should have worked either way. Did it not; or do you mean something else? – chris85 Jul 15 '15 at 03:29
  • It's working fine with 1 as you suspected. I'll approve your answer when it allows me to in a minute. But now you have me worried…not sure how to recast your answer to avoid sql injection. I know basic PDO, but not with the above code. I guess I'll keep reading. – JA4677 Jul 15 '15 at 03:32
  • I'll add some links about injections. Pretty much never pass user input directly to your query. – chris85 Jul 15 '15 at 03:33