如何同时插入和更新两个不同的表

时间:2017-12-01 08:56:36

标签: php html mysql

我想更新到一个表,但我还想插入另一个表,这个表都在一个数据库中。是否有可能在一次提交中进行,或者当然我可以更容易地分离插入和更新。提前谢谢。

<?php

error_reporting(E_ERROR); 

include("global.php");

if ($officer_name && $carno && $purpose && $schedule_date && $schedule_time 
&& $schedule_location)
{

$mysqli = new mysqli(spf, dbuser, dbpw, db); 
$stmt = $mysqli->prepare("update FEofficer set carno=?, purpose=?, 
schedule_date=?, schedule_time=?, schedule_location=? where 
officer_name=?");
$stmt1 = $mysqli1->prepare("INSERT INTO schedule (carno, purpose, 
schedule_date, schedule_time, schedule_location) VALUES (?,?,?,?,?)");
$stmt->bind_param("ssssss", $carno, $purpose, $schedule_date, 
$schedule_time, $schedule_location, $officer_name);
$stmt1->bind_param("sssss", $carno, $purpose, $schedule_date, 
$schedule_time, $schedule_location);
$result = $stmt->execute();
$result1 = $stmt1->execute();

if ($result1 == true && $stmt1->affected_rows>0) {      

     echo "<b>". $check . "</b><br>";

 }

if ($result == true && $stmt->affected_rows>0) {        
echo "<b>". $check . "</b><br>";
echo "<h2>You have successfully make a change!</h2><br>";
echo "<h3>Click <a href='distribute.php'>Here</a> to proceed back.</h3>
<br>";
}
else
{
echo "<h3>No Changes has been made</h3>";
echo '<p><h2>Please <a href="distribute.php">Click Here</a> to go back</h2>
</p>';  

}

$stmt->close();
$mysqli->close();
$stmt1->close();
$mysqli1->close();
}
else 
{
echo '<p>Please <a href="distribute.php">Click Here</a> to go back</p>';    
}

?>

提前非常感谢你。

2 个答案:

答案 0 :(得分:0)

实现目标有两种方法

1)使用MySQL后更新触发器:由于第一个表中更新的值相同(将要插入到第二个表中),因此使用After Update触发器是执行此操作的最佳方法。这将要求您的PHP代码仅触发第一个查询。插入查询(第二个)会自动被触发器触发。

2)在PHP Transactional语句下包装PHP Update和Insert语句。 例如:

try {

$db->beginTransaction();


$db->query('first query');//your first query
$db->query('second query');//Your second Query

$db->commit();
 } catch (Exception $e) {
//means something wrong with the operation, so both queries would roll back
$db->rollback();
}

此方法可确保事务的原子性,并有助于保持数据库的一致性

答案 1 :(得分:0)

我认为你需要遵循这个过程。

<?php
$carno = $this->input->post('carno');
$purpose = $this->input->post('purpose');
$schedule_date = $this->input->post('schedule_date');
$schedule_time = $this->input->post('schedule_time');
$schedule_location = $this->input->post('schedule_location');
$arr = array('carno'=>$carno,'purpose'=>$purpose,'schedule_date'=>$schedule_date,'schedule_time'=>$schedule_time,'schedule_location'=>$schedule_location);
$data = $this->db->insert('schedule',$arr);
if($data){
  $val = $this->db->where('id',$id)->update('schedule',$arr);
}
?>