vendredi 24 juin 2016

How do I stop entire content of my DB from showing when backspace is used in search box?

I'm making a livesearch feature. If I click inside the search field and hit backspace(delete button on my MAC) until the searchbox is empty, when the searchbox is clear every entry in my database shows.

Here is search form code:

    <head>    
        <script type="text/javascript">
        function searchq()
        {
            var searchTxt = $("input[name='search']").val();
            $.post("search.php" , {searchVal: searchTxt}, function(output) {$("#output").html(output)});
        }     
        </script>  
    </head>
    <body>
        <form action="search.php" method="post">
            <input type="text" name="search" placeholder="Search for members..."   onkeyup="searchq();" autofocus/>
            <input type="submit" value=">>"/>
        </form>

        <div id="output">

        </div>    
    </body>

Here is PHP code:

//collect
if (isset($_POST['searchVal'])) {

    $searchq = $_POST['searchVal'];
    //sanitize
    $searchq = preg_replace ("#[^0-9a-z]#i","", $searchq);
    $query = mysqli_query($conn, "SELECT * FROM Tutorials WHERE title LIKE '%$searchq%' OR artist LIKE '%$searchq%'") or die ("could not search");

    $count = mysqli_num_rows($query);//counts number of rows in table

    if ($count == 0) {
        $output = 'No search results';
    } else {
        while ($row = mysqli_fetch_array($query)) {
            $tit = $row['title'];
            $art = $row['artist'];
            $prev = $row['preview'];
            $wat = $row['watch'];

            $output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> <a   href="'.$prev.'" >preview tutorial</a> - <a href="'.$wat.'">watch full tutorial</a></div>';      
        }
        //echo "<p> " .$count. " search results</p>";
    }    
}
echo($output);
?>

Code is very novice, I know.

Aucun commentaire:

Enregistrer un commentaire