我可以动态下拉列表正确列出值。动态下拉数据来自的表有2个列(fruit_id,FruitType)...此表中当前列出了总共4个水果(并在我的下拉列表中)
我想要做的是在表单中显示此下拉菜单,一旦用户选择了一个水果,我想将所选水果的(fruit_id)值插入到另一个mysql表中
这是我到目前为止所用的,由于某种原因,无论我在下拉列表中选择什么,插入的(fruit_id)是4(ps,我的表中只有4个水果/下拉列表)
这是我到目前为止的代码,任何建议都表示赞赏。谢谢:))
<?php
require_once('../../../connect.php');
// dropdown
$fruit_type = '';
$sql = "SELECT fruit_id, FruitType from mydb.mytbl";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
$fruit_type.= '<option value="' . $row["fruit_id"] . '">' . $row["FruitType"] . '</option>';
}
if(isset($_POST['submit'])){
$errors = array();
require('validate.php');
if(!count($errors)){
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "INSERT INTO fruittable
(fruit_id)
VALUES ('".$row['fruit_id']."');
";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute();
}
}
if(isset($result)){
if($result){
}else{
echo '<b>Unable to Insert</b>';
print '<pre>'.print_r($stmt->errorInfo(), true);
}
}
?>
<h1>Log Fruit</h1>
<form method="post" action="add.php">
fruit type <br/>
<select name="fruit_select">
<option value=""</option>
<?php echo $fruit_type;?> <br/>
</select>
<p></p>
<br/>
<input type="submit" name="submit" value="Add" />
</form>
答案 0 :(得分:-1)
我修复了你的PDO。你必须在PDO中绑定参数。
以下是如何让代码显示每个选项:
<?php
require_once('../../../connect.php');
if ($_POST['submit']) {
$fruitid=$_POST['fruit_select'];
$insertsql = "INSERT INTO fruittable (fruit_id) VALUES (:fruitid)";
$stmt = $dbh->prepare($insertsql);
$stmt->bindParam(':fruitid', $fruitid);
$stmt->execute();
}
$fruit_type = '';
$sql = "SELECT fruit_id, FruitType FROM table";
$stmt = $dbh->prepare($sql);
$stmt->execute();
?>
<h1>Log Fruit</h1>
<form method="post" action="add.php">
fruit type <br/>
<select name="fruit_select">
<option value=""</option>
<?php
while ($row = $stmt->fetch()) {
echo "<option value='".$row['fruit_id']."'>".$row['FruitType']."</option>";
}
?>
</select>
<br/>
<input type="submit" name="submit" value="Add" />
</form>
在名为add.php的页面中使用此代码应该可以满足您的需求。它将列出水果,每当您选择水果并单击添加/提交按钮时,它会将其添加到数据库中。