Skip to content Skip to sidebar Skip to footer

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 l

Solution 1:

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:

<?php//bind to $nameif ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
        $stmt->bind_result($name);
        $OK = $stmt->execute();
    }
    //put all of the resulting names into a PHP array$result_array = Array();
    while($stmt->fetch()) {
        $result_array[] = $name;
    }
    //convert the PHP array into JSON format, so it works with javascript$json_array = json_encode($result_array);
?><script>//now put it into the javascriptvar arrayObjects = <?phpecho$json_array; ?></script>

Solution 2:

Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:

var obj = "<?phpecho json_encode($array); ?>";

You can now use obj in your javascript code

Solution 3:

For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists. Fill the <option> tags in php when building the page and you a are done.

Post a Comment for "Inserting Mysql Results From Php Into Javascript Array"