将数据库中的信息排序到表中

时间:2011-09-19 20:10:44

标签: php mysql

我正在尝试将所有这些信息整理成一个小表,我查看了一个教程,但是我遇到了问题:/

我最初有这个:

$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $aVenues);
echo $comma_separated;

// Execute query and fetch result rowset
$result = mysql_query($sql);
if ($result) {
  $rowset = array();
  while ($row = mysql_fetch_array($result)) {
    $rowset[] = $row;
  }
  var_dump($rowset);
}
else echo mysql_error();

我改为:

$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $aVenues);
echo $comma_separated;

// Execute query and fetch result rowset
$result = mysql_query($sql);
if ($result) {
  $rowset = array();
  while ($row = mysql_fetch_array($result)) {
    $rowset[] = $row;
  }

  echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $rowset)) {
    // Print out the contents of each row into a table
    echo "<tr><td>"; 
    echo $row['VENUE_NAME'];
    echo "</td><td>"; 
    echo $row['ADDRESS'];
    echo "</td></tr>"; 
} 

echo "</table>";



}
else echo mysql_error();

...这就是我现在得到的错误:/

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/nightl7/public_html/demos/autocompletejquery/index.php on line 66

我也尝试过改变

while($row = mysql_fetch_array( $rowset))

while($row = mysql_fetch_array( $result))

但所有这一切都是让错误消失,但没有显示行。感谢大家 :))))!

3 个答案:

答案 0 :(得分:1)

while($row = mysql_fetch_array( $rowset)) {
    // Print out the contents of each row into a table
    echo "<tr><td>"; 
    echo $row['VENUE_NAME'];
    echo "</td><td>"; 
    echo $row['ADDRESS'];
    echo "</td></tr>"; 
}

$rowset不是结果资源。即使它是,你已经解析了所有的结果。你想要:

foreach ($rowset as $row) {
    // Print out the contents of each row into a table
    echo "<tr><td>"; 
    echo $row['VENUE_NAME'];
    echo "</td><td>"; 
    echo $row['ADDRESS'];
    echo "</td></tr>"; 
}

答案 1 :(得分:1)

您希望遍历结果数组($rowset)并创建一个表。有几种方法可以修改它,但最简单的方法是:

更改

while($row = mysql_fetch_array( $rowset)) {

foreach ($rowset as $row) {

并保持原样。

所以第二个while循环变为:

foreach ($rowset as $row) {
    // Print out the contents of each row into a table
    echo "<tr><td>"; 
    echo $row['VENUE_NAME'];
    echo "</td><td>"; 
    echo $row['ADDRESS'];
    echo "</td></tr>"; 
}

答案 2 :(得分:1)

更改显示

的行
while($row = mysql_fetch_array( $rowset)) {

foreach($rowset as $row) {

您的第一个while循环已经获取了所有结果。它将它们存储在名为$rowset的数组中。

在PHP手册中,您可以找到如何迭代数组: http://php.net/manual/en/control-structures.foreach.php