从php中的数据库中获取结果并将其作为循环输出以在javascript中显示

时间:2013-02-04 17:36:35

标签: php javascript mysql

我有这个代码我正在尝试输出这个:

{
    title:"<?php echo $sender_fullname; ?>",
    mp3:"link",
},

在php中使用它来在javascript中显示它

//database include
require_once "db.php";

//get email from session 
$email = $_SESSION['username'];

//fetch user fullname and  id based on session
$name_query = mysql_query("SELECT fullname,id FROM users WHERE email = '$email'");
$name = mysql_fetch_object($name_query);

//fecth sender id, receiver id, audioclip, fullname and email
$query = "SELECT m.sender,m.receiver, m.audioclip, u.fullname, u.email 
                     FROM `users` AS u 
                     JOIN `messages` AS m ON m.receiver = u.id 
                     WHERE u.email = '".$email."'";

$result = mysql_query($query); 

这是循环我该怎么做才能输出相同的

while(
        $row = mysql_fetch_assoc($result)) { 
        $sender = $row['sender'];
        $sender_name_query = mysql_query("SELECT fullname FROM users WHERE id = '$sender'");
        $sender_name = mysql_fetch_object($sender_name_query);
        $sender_fullname = $sender_name->fullname;
        echo '{<br/>title:".'$sender_fullname'.",<br/>mp3:"link",<br/>},';      
    }   

3 个答案:

答案 0 :(得分:0)

你可以这样做:

while(
        $row = mysql_fetch_assoc($result)) { 
        $sender = $row['sender'];
        $sender_name_query = mysql_query("SELECT fullname FROM users WHERE id = '$sender'");
        $sender_name = mysql_fetch_object($sender_name_query);
        $sender_fullname = $sender_name->fullname;
        echo '{<br/>title:".'$sender_fullname'.",<br/>mp3:"link",<br/>},';
        print "<script>alert(\"$sender_fillname\")</script>";
    }

然后脚本标记中的代码就像javascript代码一样运行,如果你想将php变量的值放入你可以做的javascript变量中:

<?
    $mivar = "hola mundo";
    print "<script>";
    print "var mivar = \"$mivar\"";
    print "</script>";
?>

答案 1 :(得分:0)

将php导入javascript的最佳方法是通过php json_encode使用JSON。

$rows = array();
while($row = mysql_fetch_assoc($result)) { 
    $sender = $row['sender'];
    $sender_name_query = mysql_query("SELECT fullname FROM users WHERE id = '$sender'");
    $sender_name = mysql_fetch_object($sender_name_query);
    $sender_fullname = $sender_name->fullname;
    $row['sender'] = $sender_fullname;
    $rows[] = $row;
}   

echo "<script type='text/javascript'>";
echo "var rows = " . json_encode($rows) . ";";
echo "</script>";

答案 2 :(得分:0)

错误是由最后一行引起的:

echo '{<br/>title:".'$sender_fullname'.",<br/>mp3:"link",<br/>},';

应该是这样的:

echo '{<br/>title:"' . $sender_fullname . '",<br/>mp3:"link",<br/>},';

注1

你可以这样写:

$sender_fullname = $sender_name->fullname;
echo '{<br/>title:"' . $sender_fullname . '",<br/>mp3:"link",<br/>},';

很容易:

echo '{<br/>title:"' . $sender_name->fullname. '",<br/>mp3:"link",<br/>},';

注2

Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

来自http://brightmeup.info/comment.html