无法显示MySQLi SELECT查询的结果

时间:2011-03-26 22:14:00

标签: php mysqli

这是我第一次尝试将PHP与数据库(MySQLi)结合使用。我终于连接了数据库(至少,我没有收到任何错误)。

现在我尝试获取选择查询的结果并将其显示在我的表单中,但我无法显示任何内容。

我哪里错了?

这是从数据库中检索查询结果的代码:

/*Connect To DB*/
$conn = mysqli_connect($host, $user, $pwd)
        or die("Could not connect: " . mysql_error()); //connect to server
    mysqli_select_db($conn, $database)
        or die("Error: Could not connect to the database: " . mysql_error());

    /*Check for Connection*/
    if(mysqli_connect_errno()){
        /*Display Error message if fails*/
        echo 'Error, could not connect to the database please try again later.';
    exit();
    }
/*Query for states*/
$query = "SELECT StateAbbreviation, StateName FROM USState ORDER BY StateName";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>

这是显示结果的表格:

<form id="StateSelector" action="" method="post"> 
<select size="1" name="states" id="states"> 
<option value "">--Select State--</option>

<!--Loops through the states--> 


 <?
  /*Loop through through each stat and display as an option as a drop-down field */


  for($i=0; $i<$num_results; $i++) {
      $row = mysqli_fetch_assoc($result);
      echo 'option value="' .$row['StateAbbreviation'] . '">' . $row['StateName'] . '</option>' . "\n";
  }
?>
  </select>

&nbsp; Zip:
<input type="text" name="zip" size="5" /></p>
</form>

<p>Your email address:<br/>
<input type="text" name="email" size="20" /></p>

<p>Please let us know what you think:<br/>
<textarea name="feedback" rows="12" cols="40" wrap="virtual" /></textarea></p>

<p><input type="submit" value="Send feedback" /></p>

</form>

1 个答案:

答案 0 :(得分:0)

在以下行中:

echo 'option value="' .$row['StateAbbreviation'] . '">' . $row['StateName'] . '</option>' . "\n";

<代码的开头缺少<option>

这一行应该纠正到这一行:

echo '<option value="' .$row['StateAbbreviation'] . '">' . $row['StateName'] . '</option>' . "\n";



作为重现问题的快速测试用例,代码的以下部分:

<select>
<?php
    for ($i=0 ; $i<10 ; $i++) {
        // Note the missing < before "option"
        echo 'option value="' . $id . '">' . $i . '</option>';
    }
?>
</select>

在Firefox中,您将获得一个空列表,而以下是:

<select>
<?php
    for ($i=0 ; $i<10 ; $i++) {
        // The < before "option" has been added
        echo '<option value="' . $id . '">' . $i . '</option>';
    }
?>
</select>

将为您提供预期的列表 - 有十个选项。