使用多个复选框

时间:2015-11-28 06:54:56

标签: php

我在表单中有多个复选框,当点击提交按钮时会发生两种情况:

该行存在:DB中的更新行

行没有兴奋:在数据库中插入数据

<form method="post">
    <?php
    $qr=$mysqli->query("SELECT * FROM `companies`");
    for($i=0;$row=$qr->fetch_object();$i++){
        $qr2=$mysqli->query("SELECT `enable`,`price`,`id` FROM `pricing` WHERE `cid`='$row->id'");
        $row2=$qr2->fetch_object();
    ?>
        <input type="text" class="nw-prc" value="<?php echo $row2->price; ?>" name="price">
        <input type="checkbox" <?php if($row2->enable == '1'){ ?> checked <?php } ?> id="upc" name="upc[]" value="<?php echo $row2->id; ?>">

    <?php
    }
    ?>
    <input type="submit" id="up" name="up" value="">
    <?php update_price(); ?>
</form>

<?php
function update_price()
{
    global $mysqli;
    $price=$_POST['price'];
    $qr2 = $mysqli->query("SELECT `id`,`enable` FROM `pricing`");
    for ($i=0; $row2=$qr2->fetch_object(); $i++) {
        $role[$row2->id] = $row2->enable;
    }
    if (isset($_POST['up'])) {
        $isUpcSelected = isset($_POST['upc']) ? true : false;

        foreach ($role as $Id => $enable) {
            $role[$Id] = '0';
        }
        if ($isUpcSelected) {
            foreach ($_POST['upc'] as $checked) {
                if (array_key_exists($checked, $role)) {
                    $role[$checked] = '1';
                }
            }
        }
        foreach ($role as $Id => $enable) {

            $qr2 = $mysqli->query("SELECT * FROM `pricing` WHERE `id`='$Id'");
            if ($qr2->num_rows){
                $mysqli->query("UPDATE `pricing` SET `enable`='$enable' WHERE `id`='$Id'");
            }
            else{
                $mysqli->query("INSERT INTO `pricing` (`cid`,`product_id`,`price`,`enable`) VALUES ('1','$Id','$price','$enable')");
            }
        }
    }
}
?>

更新表是正确的,但插入不起作用!帮帮我PLZ!

0 个答案:

没有答案