I have an input form and I need to populate the autocomplete with data from a database. My approach seems to be working BUT I am pretty sure it's not the most efricient way. (I'm new to php, javascript) Here's my code:
//get all organizations
$org_array = '';
$sql = "SELECT id, name FROM organizations";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
foreach ($results as $row) {
$sql = "SELECT id, name FROM organizations WHERE id = :id";
$stmt = $pdo->prepare($sql);
$id = $row['id'];
$stmt->bindValue(':id', $id);
$stmt->execute();
$org_id = $stmt->fetch(PDO::FETCH_ASSOC);
//echo $org_id['name'];
$org_array = $org_array . '"' . $org_id['name'] . '",';
}
}
And here is the JS part:
<input type="text" class="form-control autocompleteOrgs" name="newOrganization" id="newOrganization" aria-describedby="newOrganizationHelp" value="<?php echo
$my_profile['organization']; ?>">
<script>
$(function() {
var orgTags = [<?php echo $org_array ?>];
$(".autocompleteOrgs").autocomplete({
source: orgTags
});
});
</script>