从下拉菜单中将数据插入数据库 - PHP MYSQL

时间:2013-05-16 12:35:51

标签: php mysql forms drop-down-menu

我的addproduct.php中有以下代码,点击提交按钮后连接到doaddproduct.php:

<tr>
<td>Category Name</td>
<td>:</td>
<td>

<select name="categoryname" id="">
<option value="">Select</option>
<?php

while($row=mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['CategoryID']; ?>">

<?php echo $row['CategoryName']; ?></option>
<?php } ?>
</select>

</td>
</tr>

因此,下拉菜单(addproduct.php)提供了数据库中的选项(表:category,column:categoryname)。例如,categoryID'1'的categoryname是food,categoryid'2'的categoryname是drink,依此类推。

现在,我想通过将选定的categoryname更改为categoryID,将选定下拉选项中的数据插入到我的数据库(表:product,column:categoryID)中。例如,我从下拉菜单中选择“饮料”,当我点击提交按钮时,程序会将数据插入到表格产品中:

| ProductID | CategoryID | ProductName |

| 123231 | 2 |可口可乐|

以下是我在doaddproduct.php中的以下代码:

<?php
    include("connect.php");

    $productname = $_POST['productname'];
    $categoryname = $_POST['categoryname'];
    $stock = $_POST['stock'];
    $price = $_POST['price'];

    if($productname == NULL || $productname == ""){
        header("location:../addproduct.php?err=You must fill product name");
    }else if($categoryname== "none"){
        header("location:../addproduct.php?err=You must choose category name");
    }else if($stock == NULL || $stock == ""){
        header("location:../addproduct.php?err=You must fill stock");
    }else if($price == NULL || $price == ""){
        header("location:../addproduct.php?err=You must fill price");
    }else if($_FILES["file"]["type"] != "image/jpeg" && $_FILES["file"]["type"] != "image/png" && $_FILES["file"]["type"] != "image/jpg"){
        header("location:../addproduct.php?err=Extention of your photo must be jpg/jpeg/png");
    }else{
        $query = $username . "-" .$fullname . "-" . $phone ."-".$email."-".$password."-".$rpassword."-".$address."-".$gender;
        $qcek = "select * from product where productname = '$productname'";
        $result = mysql_query($qcek);
        if(mysql_num_rows($result) > 0){
            header("location:../addproduct.php?err=Product name already used");
        }else{
            //for upload
            $ext = substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.'));
            move_uploaded_file($_FILES["file"]["tmp_name"],"../photos/" . $username . $ext);
            $pho = $username . $ext;

            $password = md5($password);
            //still confused here
                    $query = "insert into product values('', '', '$productname', '$pho', '$stock', '$price')";

            mysql_query($query);
            header("location:../addproduct.php?err=Success");
        }

    }

?>

我该怎么办?

2 个答案:

答案 0 :(得分:1)

如果我正确理解了问题,“通过将所选类别名称更改为categoryID。”,您似乎已经完成了大部分的工作。名为“categoryname”的下拉框只是包含id val的变量名。在查询中使用{$_POST['categoryname']},括号是必需的。

答案 1 :(得分:0)

您忘记了类别名称,请更改您的插入查询:

 $insert_query = "INSERT INTO `product ` (ProductID,CategoryID,ProductName) VALUES 
                                       ($product_id,$categoryname,'$productname')";