Skip to content
Advertisement

Inserting MySQL results from PHP into JavaScript Array

I’m trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.

e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];

What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.

This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):

JavaScript

Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what’s going on in my head)

JavaScript

I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can’t put them together.

Advertisement

Answer

In this case, what you’re doing is looping through your result array, and each time you’re printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn’t convert between the PHP array you’re getting as a result, and a javascript array.

Since you started doing it this way, you can do:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement