在PHP中解析MySQL结果时遇到问题

时间:2010-01-24 19:06:01

标签: php mysql

我正试图从数据库中提取一些结果,但我想我今天脑子已经死了。

$castquery = "SELECT * FROM cast " .
    "WHERE player_id = '" . $userid ."' ";
$castresult = mysql_query($castquery) or die(mysql_error());
$castrow = mysql_fetch_array($castresult);

...

foreach($castrow['cast_id'] as $caster) 
{
    echo "<p>";
    if ($caster['avatar_url']!='') echo "<img src=\"".$caster['avatar_url']."\" alt=\"".$caster['name']."\">";
    echo "<a href=\"?edit=".$caster['cast_id']."\">".$caster['name']."</a></p>";
}

当然,我忽视了一些显而易见的事情。

2 个答案:

答案 0 :(得分:4)

不确定您的数据库结构是什么,但$castrow['cast_id']是单个字段,而不是数组。你的意思是:

while ( $castrow = mysql_fetch_array($castresult) ) {
    // use $castrow array here
}

而不是foreach

答案 1 :(得分:1)

首先,您的代码只会像现在一样获取一行。

$castrow = mysql_fetch_array($castresult);

foreach($castrow['cast_id'] as $caster) 
{

应该是

while ($castrow = mysql_fetch_array($castresult)) {

  $caster = $castrow['cast_id'];
  ....