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


Sort information from database into a table

我正试图将所有这些信息排序到一个小表中,我在教程中查找了这个表,但我遇到了问题:/

我最初有这个:

$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))

但所做的只是让错误消失,但没有显示行。谢谢大家:(((!

您希望在结果数组($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>"; 
}
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>"; 
}

更改显示的行

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

foreach($rowset as $row) {

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

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