不运行任何查询如果其中一个查询有错误。我怎么做到这一点?

huangapple go评论94阅读模式
英文:

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_驱动程序来完成(另一个更新的理由)。您可以使用PDOmysqli来使用事务来实现此行为。您还应该利用它们的预处理语句。

  1. https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
  2. https://www.php.net/manual/en/pdo.prepared-statements.php

完成后,无论您选择哪个驱动程序(我更推荐PDO),请参阅:

  1. https://www.php.net/manual/en/mysqli.begin-transaction.php
  2. 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.

  1. https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
  2. 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:

  1. https://www.php.net/manual/en/mysqli.begin-transaction.php
  2. https://www.php.net/manual/en/pdo.begintransaction.php

huangapple
  • 本文由 发表于 2020年1月3日 21:39:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定