Reputation: 31
I want to populate one or more names in the search field, while user type one or more characters. I used the solution got from https://www.w3schools.com/howto/howto_js_autocomplete.asp. But the problem is var $countries (in my case - $cities) data shall be passed from my database.
<?php
require_once("config.php");
$sql = "SELECT cityName FROM city ORDER by cityName";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
echo $city = sprintf('"%s",', $row['cityName']);
}
?>
When I echo use $city I am getting '"Abohar","Achalpur","Adilabad","Adityapur","Adoni","Agartala","Agra","Ahmadnagar","Ahmedabad","Aizawl","Ajmer","Akbarpur","Akola","Alappuzha","Aligarh","Allahabad","Alwar","Amaravati","Ambala","Ambala', ..... But when I use -
var city = [<?php echo $city; ?>];
<script>
var city = [<?php echo $city; ?>];
autocomplete(document.getElementById("myInput"), city);
</script>
I get no response from the search input field. But if I copy and paste the results by echoing city, it responds and I am getting desired result. Please help me! Thanks.
Upvotes: 0
Views: 1050
Reputation: 2127
<?php
require_once("config.php");
$sql = "SELECT cityName FROM city ORDER by cityName";
$result = $conn->query($sql);
$CityArray = array();
while($row = $result->fetch_assoc()){
$CityArray[] = sprintf('"%s",', $row['cityName']);
}
$cityAsString = implode("",$CityArray);
?>
// Now you can use var city = [<?php echo $cityAsString; ?>];
// You will get results in city variable now
Upvotes: 1
Reputation: 33813
The problem lies in the misuse of sprintf
- the string is not being wrapped within single/double quotes correctly. You could perhaps simplify the PHP slightly like this:
require_once("config.php");
$sql="SELECT `cityName` FROM `city` ORDER by `cityName`";
$result=$conn->query( $sql );
# Fetch the entire recordset into an associative array
$data=$result->fetch_all( MYSQLI_ASSOC );
# pick the `cityName` from the array and wrap each within double quotes.
printf( '"%s"', implode('","', array_column( $data, 'cityName' ) ) );
Upvotes: 2