使用 MYSQL 数据库数据加载 Javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3288709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:03:02  来源:igfitidea点击:

Load Javascript array with MYSQL database data

phpjavascriptmysql

提问by Rony

suppose i have an javascript array "userName".I want to load it from a database table named "user".

假设我有一个 javascript 数组“userName”。我想从名为“user”的数据库表中加载它。

Can anyone help with idea or sample code?

任何人都可以帮助提供想法或示例代码吗?

Thanks

谢谢

采纳答案by Youssef

Use ajax and php as an intermediate :

使用 ajax 和 php 作为中间件:

  1. Define an empty JS array :

    var myarray = new Array();

  2. use ajax to call your php script, javascript will eval the output by PHP (note this uses prototype library):

     new Ajax.Request('myfile.php', {
    
        onSuccess : function(xmlHTTP) {
    
            eval(mlHTTP.responseText);
        }
    
    });
    
  3. Write your PHP code to grab data and print JS code (it must be valid javscript !) :

    $i=0; $q=mysql_query('select ..');
    
    while($row=mysql_fetch_array($q)){               
    
        echo "myarray[".$i."]='".$row['data']."';";
    
        $i++;  
    }
    
  4. You can check that your Js array contains data :

    alert(myarray.length); 
    
  1. 定义一个空的 JS 数组:

    var myarray = new Array();

  2. 使用 ajax 调用您的 php 脚本,javascript 将评估 PHP 的输出(注意这使用原型库):

     new Ajax.Request('myfile.php', {
    
        onSuccess : function(xmlHTTP) {
    
            eval(mlHTTP.responseText);
        }
    
    });
    
  3. 编写你的 PHP 代码来获取数据并打印 JS 代码(它必须是有效的 javscript !):

    $i=0; $q=mysql_query('select ..');
    
    while($row=mysql_fetch_array($q)){               
    
        echo "myarray[".$i."]='".$row['data']."';";
    
        $i++;  
    }
    
  4. 您可以检查您的 Js 数组是否包含数据:

    alert(myarray.length); 
    

hope this helps.

希望这可以帮助。

回答by svens

You'll have to use the mysql_connect(), mysql_select_db()functions in PHP to connect to your db. After that use mysql_query()to SELECT the fields in your user table (if your user table has the fields name and id, SELECT name, id FROM user). Then you can fetch all infos from the db with mysql_fetch_assoc()or any other mysql fetch function. Now you need to echoyour data into the javascript on your website, formatted as an array. This is complicated to get right, but you can get help from json_encode.

您必须使用PHP 中的mysql_connect(),mysql_select_db()函数来连接到您的数据库。之后使用mysql_query()SELECT 用户表中的字段(如果您的用户表具有字段名称和 ID,SELECT name, id FROM user)。然后,您可以使用mysql_fetch_assoc()或任何其他 mysql 获取功能从数据库中获取所有信息。现在您需要将echo您的数据导入您网站上的 javascript,格式化为数组。这很难做到正确,但您可以从json_encode.

To fill your array with the user names, you'd do something like this.

要使用用户名填充数组,您可以执行以下操作。

<html>
    <head>
    <script type="text/javascript">
        var userName = <?php
            // Connect to MySQL
            //mysql_connect();
            //mysql_select_db();
            $d = mysql_query( "SELECT name, id FROM user" ) or die( mysql_error() );
            $usernames = array();
            while( $r = mysql_fetch_assoc($d) ) {
                $usernames[] = $r['name'];
            }
            echo json_encode( $usernames );
        ?>;
        // Do something with the userName array here
    </script>
    </head>

回答by deceze

This creates a global uservariable in your page.

这会user在您的页面中创建一个全局变量。

<?php
    $user = /* get information from database the way you usually do */;
    // $user == array('id' => 1, 'name' => 'foo', ...);
?>

<script type="text/javascript" charset="utf-8">
    var user = <?php echo json_encode($user); ?>;
</script>

If you're looking for a dynamic AJAXy solution, follow some tutorials about AJAX.

如果您正在寻找动态 AJAXy 解决方案,请遵循一些有关 AJAX 的教程。

回答by Guillaume Lebourgeois

The best way to do that simply is to get your data in your php code, and then "write" the javascript code to generate the array in php.

最好的方法就是在你的php代码中获取你的数据,然后“编写”javascript代码以在php中生成数组。

A short example would be :

一个简短的例子是:

echo "a = new Array();";
foreach($row in $results)
{
  echo "a[$row[0]] = $row[1];";
}

My code could be quite incorrect, it's juste to give you a quick example.

我的代码可能很不正确,给你一个简单的例子是正确的。

You could also do that in a more elegant way, using json.

您也可以使用 json 以更优雅的方式做到这一点。