英文:
Do not run any query if one of the queries has an error. How do i do that?
问题
我今天注意到了一件事,认为这可能会在将来引发严重问题。让我解释一下;
示例;我有一个类似于这样的代码:
$query1 = "INSERT INTO table1(col1,col2,col3) VALUES('$col1','$col2','$col3')";
$query2 = "INSERT INTO table2(col1,col2,col3) VALUES('$col1','$col2','$col3')";
$query3 = "UPDATE table3 SET col1 = '$col1' WHERE id='$id'";
if (mysql_query($query1) && mysql_query($query2) && mysql_query($query3)) {
echo "successful message";
}
else {
echo mysql_error();
}
当发生这种情况时,非错误查询会被处理。因此,如果其中一个失败,统计信息屏幕会显示错误。
我想要做的是;
如果其中一个查询出现错误,那么就不应该处理任何查询。我该如何做到这一点?
英文:
I noticed something today and thought that it could cause huge problems in the future. Let me explain;
Example; I have a like this
$query1 = "INSERT INTO table1(col1,col2,col3) VALUES('$col1','$col2','$col3')";
$query2 = "INSERT INTO table2(col1,col2,col3) VALUES('$col1','$col2','$col3')";
$query3 = "UPDATE table3 SET col1 = '$col1' WHERE id='$id'";
if (mysql_query($query1) && mysql_query($query2) && mysql_query($query3)) {
echo "successful message";
}
else {
echo mysql_error();
}
When this happens, non-error queries are processed. So if one of them fails, the statistics screen is wrong.
What I want to do;
If there is an error in one of the queries, none should be processed. How can i do that?
答案1
得分: 3
你想要实现的功能不能使用mysql_
驱动程序来完成(另一个更新的理由)。您可以使用PDO
或mysqli
来使用事务来实现此行为。您还应该利用它们的预处理语句。
- https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
- https://www.php.net/manual/en/pdo.prepared-statements.php
完成后,无论您选择哪个驱动程序(我更推荐PDO),请参阅:
- https://www.php.net/manual/en/mysqli.begin-transaction.php
- https://www.php.net/manual/en/pdo.begintransaction.php
英文:
What you want to achieve can't be done using the mysql_
driver (another reason to update). With PDO
or mysqli
you can use a transaction to achieve this behavior. You also should take advantage of their prepared statements as well.
- https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
- https://www.php.net/manual/en/pdo.prepared-statements.php
Then once you have that done, with whichever driver you choose (PDO is preferable, IMO), See:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论