开发者

Data inser and linking tables

I am new in databases but I know how to insert data into one table with sql and php, but now I need to insert data from an array into few tables at the same time. More, I have 3 main tables and 2 linking tables , there is a linkng table between 1 and 2 and another one between 2 and 3. How to insert data into the datables simultaneously? The primary key in linking tables constitute from primary 'id' keys from main tables 开发者_StackOverflow中文版which are set on auto increment. Thanks for any help guys..


You can't insert records in more than one table at one time. You have to do it once for table manually.


You can't insert data into many tables using one INSERT statement if that's what you mean by simultaneously. Write a series of INSERT statements, one for each table. Do checks to make sure each one has run successfully.


You can insert data into table one by one only. But if you need to guarantee that data exist in all tables at once you should use transaction. It will help if something is getting wrong and you don't get inconsistent data in db. For example, in php you make it like this one:

$pdo_con = new PDO(...);
try {
$pdo_con->beginTransaction();

$pdo_con->exec("INSERT INTO table1 ....");
$table1_id = $pdo_con->lastInsertId();
$pdo_con->exec("INSERT INTO table2 ....");
$table2_id = $pdo_con->lastInsertId();
$pdo_con->exec("INSERT INTO linked_table .... values($table1_id, $table2_id )");
//repeat for other tables

$pdo_con->commit();
catch(PDOException $e) {
$pdo_con->rollback();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜