使用PHP通过MySQL创建动态表单

问题描述:

I've searched the site and was unable to find an answer.

What I get in my script is an empty pulldown menu instead of the contents from the MySQL table. I'm developing/testing code in NetBeans 8.0.2 and running in Firefox 34.0.5. Here is my code (name of file is 'domains.php') and it is exactly as shown; I didn't leave anything out.

<body>
<form method="post" action="">
<select id="domain" name="domain">

<?php

// define connection variables
$DBServer = "localhost"; // server name or IP address
$DBUser = "xxxxxxxxx";
$DBPass = "xxxxxxxxx";
$DBName = "country";
$DBPort = "3306";        

// create a connection to mysql
$conn = mysqli_connect ($DBServer, $DBUser, $DBPass, $DBName, $DBPort);

// check to see if a connection was made and, if yes, proceed
if (mysqli_connect_errno()) { // connection failed
    echo "Database connection failed: " . mysqli_connect_error();
}

// the domain query to get all domain names
$domainQuery = "select domains from domains_subdomains_cop";

// run the query -- this works elsewhere to display the contents of a table
$resultD = mysqli_query($conn, $domainQuery) or die ("Query to get data from domain failed: "
   . mysql_error());

// w/the exception of pulldown menu, the while loop works well to display records
// I've seen examples with MYSQLI_ASSOC and without it and I've tried both without success for
// pulldown menus. I use it because I haven't had any issues elsewhere in my program.

while ($row=mysql_fetch_array($resultD, MYSQLI_ASSOC)) {
    $domainName=$row[DOMAINS]; // DOMAINS is the table attribute I'm trying to pull from
    echo "<option>
       $domainName  // I accidentely put a ';' here once and that did show up in the pulldown
                    // menu.
    </option>";
}

?>

</select>
</form>
</body>

Below is an object-oriented, mysqli prepared statements version

<form method="post" action="">
<select id="domain" name="domain">
<?php
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName, $DBPort);
$stmt = $db->prepare("select `domains` from `domains_subdomains_cop`");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_object()){
    echo "<option>".$row->domains."</option>";
}
?>
</select>
</form>