将 PHP 中的 MySQL 结果插入到 JavaScript 数组中 [英] Inserting MySQL results from PHP into JavaScript Array

查看:22
本文介绍了将 PHP 中的 MySQL 结果插入到 JavaScript 数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JavaScript 中的 trie 在私人网站上创建一个非常简单的自动完成功能.问题是我所看到和尝试的示例只是在 JavaScript 数组中使用预定义的列表.

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.

例如var arrayObjects = [狗"、猫"、房子"、鼠标"];

我想要做的是使用 PHP 检索 MySQL 结果并将它们放入 JavaScript 数组中.

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

这是我目前对 PHP 所做的(JavaScript 很好,只需要填充数组):

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); 
    }
?>

然后我想使用诸如 mysql_fetch_array ($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 what's 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 } 
       ?>

我可以很好地检索回显的结果,我可以在没有 MYSQL 结果的情况下很好地操作 trie,我只是无法将它们放在一起.

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

推荐答案

在这种情况下,您所做的是循环遍历结果数组,并且每次打印出一行 var arrayObjects = [<?php stmt($name) ?>];.但是,这不会在您获得的 PHP 数组和 javascript 数组之间进行转换.

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 $name
    if ($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 javascript
    var arrayObjects = <?php echo $json_array; ?>
</script>

这篇关于将 PHP 中的 MySQL 结果插入到 JavaScript 数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆