将所选选项插入表中

时间:2012-05-19 03:38:28

标签: php

我有这个代码,我正在尝试将所选状态放在子表中。 到目前为止,它返回一个空值。我不确定这是否清楚,但我想要的是:从select选项中选择一个状态并提交它。我想将选定的州名称放入我的表子区域。

enter <?php
include("connect.php");
$state = $row['states']; //Select name
if (isset($_POST[submit])){
$query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM   state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form> here

由于

2 个答案:

答案 0 :(得分:1)

$state = $row['states']更改为$state = $_POST['states']

<?php

include("connect.php");    
if (isset($_POST[submit]))
{
   $state = $_POST['states']; //Select name
   $query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
   mysql_query($query) or die(mysql_error());
}

?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM   state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>"; // if you want to 
//get the name into table, then use like this 
//echo "<option value='$row[name]'>$row[name]</option>";  or  
//echo "<option>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form>

答案 1 :(得分:0)

试试这个:

enter <?php
include("connect.php");
if (isset($_POST[submit])){
$state = $_POST['states'];
$query = "INSERT INTO subcat (sub_name) VALUES ('".mysql_real_escape_string($state)."')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM   state");
echo '<select name="states" id="states">
<option value="">Select a state</option>';
while ($row = mysql_fetch_assoc($sql)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
<input type="submit" name="submit" value="Continue" />
</form> here

不要忘记使用mysql_real_escape_string来阻止SQL注入。我已经取代了$ state = $ row ['states']; $ state = $ _POST ['states'];

我不知道你从哪里获得了$ row ...

上面将状态名称插入数据库。