Php 如何在两个不同的mySQL表中存储相同的数据?
当新客户购买产品时,我希望在clients表中存储客户详细信息,并在orders表中存储相应的客户ID 订单表:Php 如何在两个不同的mySQL表中存储相同的数据?,php,sql,Php,Sql,当新客户购买产品时,我希望在clients表中存储客户详细信息,并在orders表中存储相应的客户ID 订单表: order_ID product client ============================ 1501 bag 1 1502 shoe 2 客户表: client_ID name ================= 1 Frank 2
order_ID product client
============================
1501 bag 1
1502 shoe 2
客户表:
client_ID name
=================
1 Frank
2 John
我找到了一个可行的解决方案,但我觉得这不是最明智的解决方案
$sql = "INSERT INTO clients(name) VALUES(?)";
$q = $con->prepare($sql);
$q->execute(array($name));
$sql = "INSERT INTO orders(product) VALUES(?)";
$q = $con->prepare($sql);
$q->execute(array($product));
$sql = 'SELECT * FROM clients ORDER BY client_ID DESC LIMIT 0, 1';
foreach ($con->query($sql) as $row) {
$client = $row['client'];
$sql = "UPDATE orders SET client = '$client' WHERE client IS NULL";
$query = $con->prepare($sql);
$query->execute();
}
我的问题是,有没有更好的办法?
备注:客户端ID是自动增量的获取插入数据库的最后一个ID:
$sql = "INSERT INTO clients(name) VALUES(?)";
$q = $con->prepare($sql);
$q->execute(array($name));
// Assuming you use PDO:
$clientId = $con->lastInsertId();
// For mysqli this would be:
// $clientId = $con->insert_id;
$sql = "INSERT INTO orders(product, client) VALUES(?, ?)";
$q = $con->prepare($sql);
$q->execute(array($product, $clientID));
获取插入到数据库中的最后一个id:
$sql = "INSERT INTO clients(name) VALUES(?)";
$q = $con->prepare($sql);
$q->execute(array($name));
// Assuming you use PDO:
$clientId = $con->lastInsertId();
// For mysqli this would be:
// $clientId = $con->insert_id;
$sql = "INSERT INTO orders(product, client) VALUES(?, ?)";
$q = $con->prepare($sql);
$q->execute(array($product, $clientID));