【发布时间】:2014-01-23 00:17:44
【问题描述】:
所以事情是这样的,我想制作一个简单的页面或模块来更新我的库存中某个产品的数量,但这些项目已经列在一个下拉列表(选择标签)上,其中它的元素来自我的数据库中的记录,因此用户只能更新数据库中的产品。
这是我的代码:
$result=mysql_query("SELECT * from inventory order by item_name");
$ctr=0;
while($inventory=mysql_fetch_array($result))
{
$print=$inventory['item_name'];
$cquantity=$inventory['quantity'];
$selected=array();
$selected[$ctr]=$print;
?>
<option value="<?php echo "$selected[$ctr]";?>"> <?php echo $print; ?></option>
<?php $ctr++;}
if (isset($_POST['submit']))
{
$add=$_POST['add'];
$subtract=$_POST['subtract'];
if ($add>0)
{
$quantity=$cquantity+$add;
$sql="Update inventory set quantity='$quantity' where item_name='$selected[$ctr]'";
mysql_query($sql) or die(mysql_error());
?>
<script>
alert("Inventory was successfully updated.");
</script>
<?php
}
else{
echo "<font color='red'>Please fill up the form correctly.</font>";}
if ($subtract>0)
{
$quantity=$cquantity-$subtract;
$sql="Update inventory set quantity='$quantity' where item_name='$selected[$ctr]'";
mysql_query($sql);
?>
<script>
alert("Inventory was successfully updated.");
</script>
<?php
}
else {echo "<font color='red'>Please fill up the form correctly.</font>";}
}
?>
我知道我的问题出在 SQL 命令中:
$sql="Update inventory set quantity='$quantity' where item_name='$selected[$ctr]'";
因为 ctr 将在循环的最后部分递增。
如何编写正确的 sql 代码,使 where 子句识别下拉列表中所选数据的值或名称?
【问题讨论】: