从Mysql select生成Javascript数组

时间:2012-02-02 15:28:58

标签: php mysql

我想知道是否有人可以提供帮助 - 我想选择一个表并使用返回值创建一个Javascript数组。这是我到目前为止所做的:

con = mysql_connect("localhost","usrname","password");

if (!$con) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);
$ql = "SELECT theMessage FROM email_message";
$result = mysql_query($ql) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
    $allMessage = $row['theMessage'] . " ";
}

$arr = array($allMessages);
$script = '<script>var newArr = new Array(' . implode(' ', $arr) . ');</script>';
echo $script;

但相反,它只是向我展示了这样的空数组:var newArr = new Array();

2 个答案:

答案 0 :(得分:3)

更改行

$allMessage = $row['theMessage'] . " ";

$allMessages[] = $row['theMessage'] . " ";

(在变量名中添加s,然后添加[]) 因为每次读取新行时都会覆盖结果,然后从不同的(空)变量中读取!

现在你应该不使用空格来破坏数组,你应该用“,”或“”,“”来内展它,具体取决于存储的数据。

您也可以将输出直接放入fetch-loop中,但这只是一个想法。

你真正应该考虑的是阅读json_encode()和json_decode():

http://www.php.net/manual/en/function.json-encode.php

http://www.php.net/manual/en/function.json-decode.php

希望我能提供帮助。

答案 1 :(得分:0)

你考虑过使用json_encode()吗?

我会使用mysql_fetch_assoc,然后在我的'while'循环中,将每个项目推送到php数组,然后使用内置的json_encode函数创建一个可以轻松使用的javascript对象。

编辑:请勿使用mysql_个功能。 PDO和MySQLi中有类似的功能来实现相同的目标。使用那些。