开发者

Unable to display result of MySQLi SELECT query

This is my first attempt at using PHP with a Database (MySQLi). I finally got the database connecting (at least, I am not getting any errors).

Now I trying to get the result of a select query and display it in my form, but I canno开发者_如何学编程t get anything to display.

Where am I going wrong?

This is the code to retrieve the query results from the database:

/*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);
?>

This is the form where the results should display:

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


In the following line :

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

You have a missing < at the beginning of the <option> tag.

That line should be corrected to this one :

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



As a quick test-case to reproduce the problem, the following portion of code :

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

Will get you, in Firefox, an empty list, while the following one :

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

Will get you the expected list -- with ten options.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜