mysql离开了最后一行连接回声

时间:2012-05-29 14:53:11

标签: php mysql

我有两张表classifiedsstate

分类广告 - id, title, state_id

州 - id, statename

我试图回应州的州名。我已经尝试过这个查询,但它只回显了最后一行。

    <?php
    $query  = "SELECT * FROM classifieds ";
    $result = mysql_query($query) or die(mysql_query());
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
   ?>

    <div>
   <span>Title: <?php echo $row['title'];?> </span>
    </div>

   <div>
   <span>Name: <?php echo $row['name'];?> </span>
    </div>

      $q = mysql_query("SELECT * FROM classifieds AS C
    LEFT JOIN  state AS S
    ON C.state_id = S.id");
    $z = array();

    while($state=mysql_fetch_array($q))
     {
      array_push($z,$state["statename"]);
     }

     ?>
    <div>
    <span>State: <?php foreach($z as $location) { echo $location; } ?></span>

    </div>

  <?php } // End of the first while loop ?>

由于

4 个答案:

答案 0 :(得分:2)

您需要在echo循环内移动while命令。否则只有在经过所有行后才会回显。

 <?php
 $q = mysql_query("SELECT * FROM classifieds AS C
LEFT JOIN  state AS S
ON C.state_id = S.state_id");
 while($state=mysql_fetch_array($q)){
    echo "Location: ".$state["statename"];
 }
 ?>

修改:根据您更新的代码,我可以看到您的问题是您首先获得所有classifieds的列表,然后再次添加相同的列表。您根本不需要执行第一个查询,只需要执行第二个查询。

 <?php
 $q = mysql_query("SELECT C.*, S.statename 
       FROM classifieds AS C
       LEFT JOIN  state AS S
       ON C.state_id = S.state_id");
 while($row=mysql_fetch_array($q)){
    echo "Title: ".$row["title"]."<br />";
    echo "Name: ".$row["name"]."<br />";
    echo "Location: ".$state["statename"]."<br />";
 }
 ?>

答案 1 :(得分:1)

您在每次循环迭代时都会覆盖$z的值。如果它有来自数据库的多个结果你也想让$ z成为一个数组,然后使用array_push()将$ state [“statename”]的值附加到$ z

<?php
$q = mysql_query("SELECT * FROM classifieds AS C
    LEFT JOIN  state AS S
    ON C.state_id = S.state_id");

$z = array();

while($state=mysql_fetch_array($q)){
    array_push($z,$state["statename"]);
}
?>

然后在循环后使用它来检查你的数组......

<?php print_r($z); ?>

...这将循环遍历数组并执行您需要的格式

<?php
foreach($z as $location) {
    echo 'Location ' . $location . '<br/>';
}
?>

答案 2 :(得分:0)

您需要将echo语句放在while循环中。

答案 3 :(得分:0)

试试这个:

<?php
     $q = mysql_query("SELECT * FROM classifieds AS C LEFT JOIN  state AS S ON C.state_id = S.state_id");

      while($state=mysql_fetch_array($q))
      {
           $z =$state["statename"];
           echo "Location: " . $z . PHP_EOL;
      }
 ?>

在原始代码中,循环外的echo语句只会执行一次,即只会显示最后一次分配$z。将它放在循环中可确保为每行数据执行它。