Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to make a very simple auto-complete 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.

eg. 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):

<?php 
    $mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
    if (!$mysqli)
    {
        die('Could not connect: ' . mysqli_error($mysqli));
    }
    if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
        $stmt->bind_result($name);
        $OK = $stmt->execute();
    }   
while($stmt->fetch()) 
    {
     printf("%s, ", $name); 
    }
?>

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 whats going on in my head)

<script> -- this is the javascript part
(function() {
    <?php while $stmt=mysql_fetch_array($name))
     {
       ?>
        var arrayObjects = [<?php stmt($name) ?>];
    <?php } 
       ?>

I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together, any help would be greatly appreciated and if I am going the completely wrong way about it please let me know.

Thanks,

Adam

share
 
Consider using Ajax calls and passing data in JSON format instead of this cross-language madness that you have now –  Juribiyan 9 secs ago
add comment

1 Answer

Use json_encode to turn your PHP array into a javascript object. e.g.:

var obj = "<?php echo json_encode($array); ?>";
share
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.