phpmysqlajaxlivesearch

PHP live search not getting the existing row in database


So, I'm making PHP live search with php,jquery and mysql. the data that being search isn't showing in my page despite the data is exist in the database.

rowCount() is showing the correct total of rows, but the page isn't showing all the rows.

here's my php code

<?php
if(isset($_POST['keyword'])){
    $key = $_POST['keyword'];

    $findPerusahaan = "SELECT * FROM perusahaan_instansi WHERE badan_hukum LIKE '%$key%' OR merek LIKE '%$key%' ";
    $stmt = $conn->prepare($findPerusahaan);
    $stmt->execute();
    $data =$stmt->fetch(); 

    foreach($stmt as $row){
        echo $row['badan_hukum']."<br>";
    }
    //print_r($stmt);
    echo $stmt->rowCount();
}

?>

and here it is the page

<input onkeyup="myFunction()" type="text" id="myInput" class="form-control" 
id="perusahaan" name="perusahaan" placeholder="PT....." required>
<div id="perusahaan"></div>


<script>
function myFunction() {
console.log($('#myInput').val());
var keyword = $('#myInput').val();

$.ajax({
        type:'POST',
        url: 'index.php?modul=form_submit&action=perusahaan',
        data: {'keyword': keyword },
        success:function(data){
                console.log(data);
                $('#perusahaan').empty();
                $('#perusahaan').append(data);
        }
    });

   }
   </script>

Here is the result, thanks for any help result


Solution

  • $data contains your array of rows, not $stmt!

    Change this:

    $data = $stmt->fetch(); 
    foreach($stmt as $row){
        echo $row['badan_hukum']."<br>";
    }
    

    to this:

    $data = $stmt->fetchAll(); 
    foreach($data as $row){
        echo $row['badan_hukum']."<br>";
    }