mysql多行更新耗时超过应有的时间

时间:2016-03-21 03:17:28

标签: php mysqli

我正在对我的数据库运行一个简单的更新,该更新来自一个包含大约100个复选框的表单。因此它循环约100次,但需要接近10秒才能完成。由于表单只传递选中的复选框,我首先将“选定列”中的所有值设置为0,然后根据传入的复选框ID将所选值设置为1。我觉得这应该花费几秒钟而不是10秒。

我是否正在做一些导致进程拖动的内容?

if (isset($_POST['validCall']))
{
    $sql = "UPDATE salesTable SET selected = 0 WHERE programID = ?";

    if ($stmt = $mysqli->prepare($sql)) 
    {
        $stmt->bind_param('i', $_POST['program']);

        $stmt->execute();
        $stmt->close();
    }

    foreach($_POST as $key =>$value)
    {
        if ($key != "validCall" && $key != "program")
        {
            $sql = "UPDATE salesTable SET selected = 1 WHERE ID = ?";

            if ($stmt = $mysqli->prepare($sql)) 
            {
                $stmt->bind_param('i', $key);

                $stmt->execute();
                $stmt->close();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

更改foreach以便它只运行一个查询

$ids=array();
foreach ($_POST as $key=>$value){
    if ($key != "validCall" && $key != "program"){
        $ids[] = $key; // get the ids to use
    }
}


// creates a string containing ?...
$clause = implode(',',array_fill(0,count($ids),'?'));


$stmt = $mysqli->prepare( "UPDATE salesTable SET selected = 1 WHERE ID = ($clause)";

call_user_func_array(array(
        $stmt,
        'bind_param'
),$ids);
$stmt->execute();

答案 1 :(得分:0)

$sql = "UPDATE salesTable SET selected = 1 WHERE ID = ?";

if($stmt = $mysqli->prepare($sql)){
    $stmt->bind_param('i', $key);

    foreach($_POST as $key =>$value)
    {
        if ($key != "validCall" && $key != "program")
        {            
            $stmt->execute();     
        }
    }
}

$stmt->close();

希望这会有所帮助:)