php - How to check if both query excecuted successfully?
问题描述
I want to INSTERT into 2 different tables. People will complete a form, where they enter their user data, and their company data. I tested this form, and when everything correct it's fine but...when the user data is ok, and the company data has errors, the user insert runs and I don't want it. Vica versa.. My code right now: (just a markup)
$sql = "INSERT INTO user (name, email, password) VALUES (:username, :email, :password)";
$stmt = $dbh->prepare($sql) {
... //bind parameters
if($stmt->execute()){
echo "Successfully registered user";
$sql = "INSERT INTO company (title, number, address) VALUES (:title, :number, :address)";
$stmt = $dbh->prepare($sql) {
... //bind parameters
if($stmt->execute()){
echo "Successfully registered company";
}
}
}
}
unset($stmt);
I want to check both, and when there is no error, then run both query. How do I nest it?
解决方案
您可以将 transactions beginTransaction
, rollBack
,commit
与 try 和 catch 一起使用。
$dbh->beginTransaction()
try {
$sql = "INSERT INTO user (name, email, password) VALUES (:username, :email, :password)";
$stmt = $dbh->prepare($sql) {
... //bind parameters
if($stmt->execute()){
echo "Successfully registered user";
$sql = "INSERT INTO company (title, number, address) VALUES (:title, :number, :address)";
$stmt = $dbh->prepare($sql) {
... //bind parameters
if($stmt->execute()){
echo "Successfully registered company";
}
}
}
}
} catch(\Exception $e)
$dbh->rollBack();
}
$dbh->commit();
unset($stmt);
推荐阅读
- javascript - React Native 添加多个表单 onPress 按钮和 onchangeText 问题
- php - 在 SQL 查询中获取日期
- macos - 在 macOS 的 SceneKit 中无法显示 stl 文件
- python - 如何隐藏按钮以及如何在其上进行新的选项卡重定向?
- apache-kafka - 如何通过kafka生产者通知用户到消费者进程
- r - mlr:在 CV 循环中检索 generateFilterValuesData 的输出
- android-studio - 如何查看 android studio 的所有 avd 列表(不启动 android studio)然后从 linux mint 的命令行启动 avd
- python - 如何从触发它的作业中获取下游构建的数量?
- shell - 根据输入打印星号
- c# - 如何使用工厂/策略模式返回不同的响应类型