简体   繁体   中英

PHP MYSQL search same keyword with multiple tables

I'm try to create a query which will search four different tables with one keyword to bring all the items which are list under that location.

I have four tables - Country - State - County - City

for eg UK -> England -> West Midlands -> Birmingham

When user types in west Midlands i wont to see all the items including items under birmingham, Walsall, wolverhampton

This what I came up with

$location = $_POST['location'];
$city_sql = " SELECT * FROM city";

$city_result = $db->query( $city_sql );
$new_array=array();
$i=0;
while ($fetch_sql = $db->fetch_object($city_result) ){

    if ( strcmp(soundex(strtolower($fetch_sql->name)), soundex(strtolower($location))) == 0 ) { 
        $new_array[$i]['name'] = $fetch_sql->name;
        $new_array[$i]['code'] = $fetch_sql->name;
        $i++; 
    }
}

$k=0;
for ( $j=0; $j < sizeof($new_array); $j++ ){
    $i = similar_text(strtolower($new_array[$j]['name']), strtolower($db->escape_value($location)), &$similarity_pst);
    if( $i > $k && $i > 7 ){
        $k = $i;
            $city_db_name = $new_array[$j]['name'];
            $city_code = $new_array[$j]['code'];
    }
}

Please let me know if you have any idea.

PHP MYSQL search same keyword with multiple tables

You should use SQL features to get your data, not PHP's.

If I correctly understood, you want to get data from several tables and several columns. Change your query like that:

SELECT
  -- list of considered columns
  col1,
  col2,
  col3
  -- ...
FROM
  City
JOIN
  State ON State.state_id = City.state_id
JOIN
  Country ON Country.country_id = State.country_id
WHERE
  col1 LIKE '%keyword%'
  OR col2 LIKE '%keyword%'
  OR col3 LIKE '%keyword%'
  -- ...

Like that, you will get columns you need containing your keyword. For example, if the table City contains {'Paris', 'paramatta', 'Porto'}, using the keyword Par , and the query SELECT name FROM city WHERE name LIKE '%Par%' will return you { 'Paris', 'paramatta' }

By the way, the link between countries, cities, etc. should be represented backward in your database: Country <- State <- City

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