0

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>
1
  • If the code works and you just want to know if there is a better way, you should post it in Code Review instead. Commented Feb 23, 2019 at 17:56

1 Answer 1

1

You don't need to fetch organizations one more time, better approach would be:

$org_array = '';
$sql = "SELECT id, name FROM organizations";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
    $org_array = implode(',', array_column($results, 'name'));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.