-1

我正在尝试从我的数据库中在我的网站上显示评论。我知道我的连接正常,如 $test 所示(显示“Array”)。

如何将数组转换为可用信息?这是我最好的镜头,但它没有显示任何内容:

<?php
$connect;

$sql_get_topic_info = "SELECT * FROM wall ORDER BY time ASC"; 
$res_get_comments_info = mysql_query($sql_get_comments_info); 
$num_get_comments_info = mysql_numrows($res_get_comments_info); 
$test = mysql_fetch_array(mysql_query($sql_get_topic_info)); //just to make sure the connection is working
echo $test; //displays "Array"


//Runs comment loop 
$i=0; 
while ($i < $num_get_comments_info) { 

$sel_comments_info_time = mysql_result($res_get_comments_info,$i,"time"); 
$sel_comments_info_message = mysql_result($res_get_comments_info,$i,"message"); 
$sel_comments_info_company = mysql_result($res_get_comments_info,$i,"company"); 

echo "<li>Company: $sel_comments_info_company<br/>"; 
echo "Comment: $sel_comments_info_message <br/>";
echo "$sel_comments_info_time"; 
echo "</li>"; 

$i++; 
} 
?>

更新的脚本:(来自下面的答案)

$result = mysql_query("SELECT company, message FROM wall");

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
printf ("company: %s  message: %s", $row["company"], $row["message"]);
}

mysql_free_result($result);

打印:

company: company 1 message: message 1company: company 2 message: message 2company: company 3 message: message 3
4

1 回答 1

1

不鼓励使用 of mysql_,您应该改用mysqli_函数。

mysql_fetch_array文档:

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);  
}

用于print_r($test)查看数组以查看其格式。然后您可以使用上面的循环以您想要的任何顺序显示它的各个部分。数据库中的每一列都在结果行中

row = [col1, col2, col3...]

您可以使用数组索引访问它们$row[0], $row[1]...。您可以通过查看数据库中列的顺序或查看它在print_r. 然后你可以按照你想要的顺序回显它。

于 2012-07-01T01:07:29.807 回答