Josel Parayno Josel Parayno - 3 years ago 169
MySQL Question

empty string retrieve all value in mysql using php

i have a users table which contains multiple columns like id, username and password and i'm trying to search for the username, but whenever i tried to input empty string it shows all the row, my question is how can i validate the result when i put empty string there should be no result.

<?php

include "db.php";
include "function.php";

if(isset($_GET['keywords'])){
global $connection;
$keyword = ($_GET['keywords']);
$result = searchData($keyword);
}

?>

<form action="search.php" method="_GET">
<label>
Search
<input type="text" name="keywords">
</label>
<input type="submit" name="search">
</form>

<div class="result-count">
<?php
if(!isset($result)){
echo "enter something to search.";
}else{
echo "$result->num_rows results.";?>
</div>

<?php
if($result->num_rows){
while($r = $result->fetch_object()){
?>
<div class="result">
<a href="#"><?php echo $r->username; ?></a>
</div>
<?php
}
}
}


function.php

<?php

function searchData($keyword){
global $connection;

$query = ("
SELECT username
FROM users
WHERE username LIKE '%{$keyword}%'
");
$result = mysqli_query($connection, $query);

return $result;
}
?>

Answer Source

Use the required HTML attribute. The form wont submit if the textbox is doest not have a value.

Like this:

<input type='text' name='keywords' required>

And then you can also put in place a second measure in your php script like:

if(isset($_REQUEST['search'])){
    if(!isset($_REQUEST['keywords']) || empty($_REQUEST['keywords'])){
         echo "<script>window.alert('Keyword required');
    }else{
        //continue with execution & fetch db
    }
}

And also use LIKE %string% in your sql statement

Hope that helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download