在列中输出while($ row = mysqli_fetch_array($ result))

时间:2014-07-07 12:01:05

标签: php mysql

我有一个简单的问题,但我错过了一些东西。我希望此查询的输出为4列:

$result = mysqli_query($con,"SELECT * FROM countries");
echo "<table>";
 while($row = mysqli_fetch_array($result))
   {     echo "<tr>";
  for ($x=1; $x<=4; $x++);
{
      echo "<tr><th></th>";
          echo "<td>";
                        echo "<a href='http://localhost/loc.php?loc=" .$row['countryID']. "'>"          ; echo $row['country'] ; echo "</a> ";
            echo  "</td>";
echo "</tr>";
}
  }
echo "</table>";

我只有1列所有国家/地区或1个国家/地区4次?我错过了什么或做错了什么。它对我来说很长一段时间。

5 个答案:

答案 0 :(得分:0)

而不是使用Select * From ... 你需要使用Select column1, column2, column3...

答案 1 :(得分:0)

我认为你打印的"<tr>"标签太多了

试试这段代码:

$result = mysqli_query($con,"SELECT * FROM countries");
echo "<table>";
while($row = mysqli_fetch_array($result)) {     
  echo "<tr>";
  for ($x=1; $x<=4; $x++) {
    echo "<td>";
    echo "<a href='http://localhost/loc.php?loc=" .$row['countryID']. "'>"; 
    echo $row['country'] ;
    echo "</a> ";
    echo  "</td>";
  }
  echo "</tr>";
}
echo "</table>";

答案 2 :(得分:0)

试一试。

<table>
    <tr>
        <th>Country</th>
    </tr>
    <?php $result = mysqli_query($con,"SELECT * FROM countries");
    while($row = mysqli_fetch_array($result)):
    ?>
    <tr>
        <td> <a href="http://localhost/loc.php?loc=<?php echo $row['countryID']?>"><?php  echo $row['country']; ?></a> </td>
    </tr>
    <?php endwhile;?>

</table>
    <?php $result->close();?>

答案 3 :(得分:0)

<?php

// this should be placed in some Controller
$result = mysqli_query($con, "SELECT `id`, `name` FROM `countries` LIMIT 4");
$countries = array();
while ($row = mysqli_fetch_array($result)) {
    $countries[] = $row;
}

?>

<!--and this in some view-->
<table>
    <tr>
        <?php for ($i = 0; $i < 4; $i++): ?>
        <td>
            <?php if (isset($countries[$i])): ?>
            <a href="http://localhost/loc.php?loc=<?php echo $countries[$i]['id']; ?>" title=""><?php echo $countries[$i]['name']; ?></a>
            <?php else: ?>
            &nbsp;
            <?php endif; ?>
        </td>
        <?php endfor; ?>
    </tr>
</table>

无论如何,你不应该混淆HTML和PHP代码。如果可以尝试使用一些模板语言。

答案 4 :(得分:0)

<?php
$result = mysqli_query($link, "SELECT `countryID`, `country` FROM `mydb`.`countries`");
echo '<table>
';
$loop = 0;
while($row = mysqli_fetch_array($result)) {
  if ($loop == 0) {
    echo '  <tr>
    ';
  }
  if ($loop == 5) {
    echo '  </tr>
    ';
    $loop = 0;
  }
  else {
    echo '    <td><a href="http://localhost/loc.php?loc=' .$row['countryID']. '">' . $row['country'] . '</td>
    ';
    ++$loop;
  }
  echo "  </tr>";
}
echo "</table>";
?>

注意在sql中使用反引号,以确保你没有使用保留字。

还要注意回声中单引号和双引号的交换。首先,双引号是html中的约定。其次,php运行速度更快。 “php将解析此文本”,而“此文本将按”原样“读取。”