简体   繁体   中英

php pdo insert,update into one table in mean time insert query to other table too

this is the tables

tbl_one
id---int
name-var


tbl_tow
id----int
name--var

this is how it will insert with php pdo,

public function insert() {  
        $stmt9 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
        $stmt9->bindParam(':name' ,$this->name);
        $stmt9->execute();
        if($stmt9){
            echo "Added";
        } else {
            echo "error";
        }
    }

here the idia is to insert in both tables in one time, and delete from both tables in one time.

is it possible here

NOTE: i can not use trigger as i have already setup in other case so mysql is not supporting multi trigger in one time or action.

regards

Is this not what you're after?

public function insert() {  
    $stmt9 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
    $stmt9->bindParam(':name' ,$this->name);
    $stmt9->execute();

    $stmt10 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
    $stmt10->bindParam(':name' ,$this->name);
    $stmt10->execute();
    if($stmt9 && $stmt10){
        echo "Added";
    } else {
        echo "error";
    }
}

Basically you double up the queries inside your function, so you can "manually" insert trails to your log table. Sorry if I've misunderstood you.

I assume that you are looking for a transaction.

All changes performed by queries will be live only when you commit a transaction, if something fails you may simply do a rollback and nothing will happen at all.

This is useful if you have inserts in multiple tables and want to be sure that changes are only made when all queries were a success!

Example:

public function insert() {  

    //This will start a transaction and turn-off auto-commit of queries.
    $this->conn->beginTransaction(); 

    $stmt9 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
    $stmt9->bindParam(':name' ,$this->name);
    $stmt9->execute();

    $stmt10 = $this->conn->prepare("INSERT into tbl_two (name) VALUES (:name)");
    $stmt10->bindParam(':name' , $someOtherName);
    $stmt10->execute();

    if($stmt9 && $stmt10){
        $this->conn->commit(); //This will save your changes
    } else {
        $this->conn->rollBack(); //This will undo your changes       
    }
}

Simple as that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM