PHP PDO将命令放入事务问题中

时间:2011-08-10 10:16:59

标签: php sqlite pdo

我正在使用PHP PDO来处理数据库SQLITE3。有人可以告诉我如何将这些命令放在一个交易中吗?

            $db = new PDO('sqlite:/var/db/fan_coil.db');
            $sql = 'DELETE FROM fan_coil_plan WHERE fan_coil_id = :fan_coil_id;';
            $sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
            $sth->execute(array(':fan_coil_id' => $fan_coil_id));

            $sql = ' DELETE FROM fan_coil_working_mode WHERE fan_coil_id = :fan_coil_id;';
            $sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
            $sth->execute(array(':fan_coil_id' => $fan_coil_id));


            //****************** inserting working mode *************************************************************************************************


                $i = 0;
                $sql = 'INSERT INTO fan_coil_working_mode
                (fan_coil_id,working_mode, temperature_set_point, max_positive_temperature,min_positive_temperature,mode_type,max_fan_speed)
                VALUES(:fan_coil_id,:working_mode,:temperature_set_point,:max_positive_temperature,:min_positive_temperature,:mode_type,:max_fan_speed)';
                $sth = $db->prepare($sql);

            foreach ($modes as $key => $value) {
//file_put_contents('error.txt',$value['temperature_set_point'], FILE_APPEND );
                $working_mode = '0'; //treba da se izbaci ova kolona iz tabele
                $temperature_set_point = $value['temperature_set_point'];
                $max_positive_variation = $value['max_positive_variation'];
                $min_positive_variation = $value['min_positive_variation'];
                $max_fan_speed = $value['max_fan_speed'];
                $mode_type = ++$i;

                $sth->execute(array(':fan_coil_id' => $fan_coil_id, ':working_mode' => $working_mode, ':temperature_set_point' => $temperature_set_point, ':max_positive_temperature' => $max_positive_temperature, ':min_positive_temperature' => $min_positive_temperature, ':mode_type' => $mode_type, ':max_fan_speed' => $max_fan_speeed));
            }

1 个答案:

答案 0 :(得分:2)

$db = new PDO('sqlite:/var/db/fan_coil.db');
$db->beginTransaction();

try {
    // your code
    $db->commit();
}catch(PDOException $e) {
    $db->rollBack();
    throw $e;
}