简体   繁体   中英

fetch data from two tables in php without joining the tables

I'm still learning PHP and MySql and having difficulty with search bar. My problem is that I was able to select two tables from the database but i'm having trouble with the while loop where it is throwing everything at the search bar or sometimes nothing. I'm using typeahead.js plugin for this. I want the countries to show up first and then domains should be suggested and I dont want to join the tables. Please help.

This is my script :

    <script>
    $(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'typeahead',
        remote:'search2.php?key=%QUERY',
        limit : 30
    });
}); 
</script>

This is my php:

    <?php
    $key=$_GET['key'];
    $array = array();
    $con=mysql_connect("localhost","root","");
    $db=mysql_select_db("test_db",$con);
    $query=mysql_query("select * from tbl_sample where country LIKE '%{$key}%' AND domain LIKE '%{$key}%' ");

    while($row=mysql_fetch_assoc($query)){
      $array[] = $row['country'];
      $array[] = $row['domain'];
    }
    echo json_encode($array);
?>

What you're asking is a bit vague given you haven't described the second table to us at all, so I assume you just want to do two separate selects from the same table. That's done like this and will place countries first:

$query=mysql_query("select country as 'result' from tbl_sample where country LIKE '%{$key}%' UNION select domain as 'result' from tbl_sample where domain LIKE '%{$key}%' ");

while($row=mysql_fetch_assoc($query)){
  $array[] = $row['result'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM