PHP和JS代码未执行

时间:2013-03-08 10:44:56

标签: php javascript

我在我的网页上有这个PHP和JS代码。

<?php
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());;
$counter = 0;
// write the values from the database into the javascript array
    echo "<script type='text/javascript'>";
    echo "this.styleListArray = new Array();";
    if ($result) {
        while($row = mysql_fetch_array($result)) {
            echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " .          $row['user_fname'] . "';"); // displays 'lname, fname'
            $counter += 1;
        }
    }
echo("</script>");

?>

问题是,当我执行包含代码的页面时,此代码的一部分不会被执行,它只是在页面上显示为一个简单的文本:

"); echo "this.styleListArray = new Array();"; if ($result) { while($row =   mysql_fetch_array($result)) { echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname' $counter += 1; } } echo(""); ?> 

我试图搞清楚,但我无法得到它,如果你能帮助兄弟,那就太好了。

3 个答案:

答案 0 :(得分:0)

尝试重写您的代码:

include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());
$counter = 0;
// write the values from the database into the javascript array

echo <<<HTML
<script type='text/javascript'>
this.styleListArray = new Array();
HTML;

$strLine = '';

if ($result) {
    while($row = mysql_fetch_array($result)) {
        $strLine.= "this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"; 
        $counter += 1;
    }
}

echo $strLine;

echo("</script>");

答案 1 :(得分:0)

首先更改您的查询以使用mysqli或pdo连接 其次尝试以下代码

$sql = 'SELECT URL FROM remontee_nlf ORDER BY URL ASC';
$res = mysql_query($sql, $con);
$rows = array();
while ($row = mysql_fetch_assoc($res))
    $rows[] = $row['URL'];

$str = implode('", "', $rows);
$data = '["'.trim($str).'"]';

echo '<script type="text/javascript">';
echo "var data = $data;";
echo 'console.log(data)';
echo '</script>';

检查控制台日志。

enter image description here

答案 2 :(得分:-1)

$result = mysql_query($query) or die (mysql_error());;将其更改为

$result = mysql_query($query) or die (mysql_error());

还要确保$row['URL']$row['user_fname']可用。