2011-03-26 54 views
0

这是我第一次尝试使用PHP与数据库(MySQLi)。我终于得到了数据库连接(至少,我没有得到任何错误)。无法显示MySQLi SELECT查询的结果

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

我哪里错了?

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

/*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> 

回答

0

在下面的行:

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

您在的开头缺少< 210标签。

该行应该被校正到这样一个:

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> 

会给你预期的清单 - 有十个选项。