php - 使用 PHP 和 MySQL 创建动态表单

标签 php mysql forms

我搜索了该网站,但找不到答案。

我在脚本中得到的是一个空的下拉菜单,而不是 MySQL 表中的内容。我正在 NetBeans 8.0.2 中开发/测试代码并在 Firefox 34.0.5 中运行。这是我的代码(文件名是“domains.php”),它完全如图所示;我没有遗漏任何东西。

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

最佳答案

下面是面向对象的 mysqli 准备好的语句版本

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

关于php - 使用 PHP 和 MySQL 创建动态表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27714399/

相关文章:

php - 选择数据库中尚未存在的不同值

php - fatal error : Out of memory, 但我确实有足够的内存 (PHP)

php - 创建一个有效的单词计数器,包括中文/日语和其他重音语言

php - 插入具有更高顺序值的新行时,如何更改表中的顺序值?

java - 在jsp中显示查询中的非空值

用于在 HTML 中查找带有输入标签的表单的 C# 正则表达式?

javascript - 使用JS将表单字段标记为只读

php - 如何将子值添加到新数组?

不创建键的 PHP array_replace

php - PDO 准备好的语句导致 SIGABRT