I have a mysql table with multiple rows
ID, country, city, region
I have a search working with jquery-ui autocomplete, which currently autocompletes city searches like so:
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT city,country FROM location WHERE city LIKE :term LIMIT 10');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['city'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
I would like to display the country next to the city, so Los Angeles
would become Los Angeles, US
In php you can append a string by using a '.' For example:
$mystring = 'part one' . 'part two';
echo $mystring; //-> will product: part onepart wo
You can also let php interpret a string to delimiting with '"' (double quotes)
$myvar = "boat";
$mystring = "One day I'll buy a {$myvar}";
echo $mystring; //-> will produce: One day I'll buy a boat
The below should work ok. Good luck!
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT city,country FROM location WHERE city LIKE :term LIMIT 10');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['city'] . ', ' . $row['country'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
Another alternative way to solve this would be to append the string in your SQL
SELECT CONCAT(city, ', ', country) AS location FROM location WHERE city LIKE :term LIMIT 10