MySQL 更新或插入或死亡查询
做这样的事情是否有效,我从来没有看到超过 1 个 or 运算符:
$insert = 'INSERT into fhours (' .$cols . ') VALUES ('.$query.')';
$update = sprintf("UPDATE fhours SET %s WHERE fname='$fname' AND lname='$lname'", $field_list);
$result = $db->query($update) or $db->query($insert) or die('uhoh');`
Is it valid to do something like this, I never see more than 1 or operator:
$insert = 'INSERT into fhours (' .$cols . ') VALUES ('.$query.')';
$update = sprintf("UPDATE fhours SET %s WHERE fname='$fname' AND lname='$lname'", $field_list);
$result = $db->query($update) or $db->query($insert) or die('uhoh');`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这有两个问题。
首先,您可以使用参数化查询。 看看 PDO,这会对你有很大帮助。这不仅对于多次插入来说更快,而且您不必太担心 SQL 注入。
第二个是你可以使用 MySQL 的
ON DUPLICATE KEY UPDATE
为您解决这个问题。否则,当你的查询失败时,你不知道失败的原因。它可能根本不是重复的密钥问题!除此之外,从
或
的角度来看代码就很好。There are two problems with this.
The first is that you can be using parameterized queries. Look at PDO, this will help you greatly. Not only is this faster for multiple inserts, but you don't have to worry about SQL injection so much.
The second is that you can use MySQL's
ON DUPLICATE KEY UPDATE
to take care of this issue for you. Otherwise, when your query fails, you don't know why it failed. It may not have been a duplicate key issue at all!Other than that, the code from the standpoint of
or
is just fine.您可以根据需要链接任意多个逻辑运算符。
您还应该考虑 mysql 的“重复键”机制。
http://dev.mysql.com/doc/refman /5.0/en/insert-on-duplicate.html
You can chain as many logical operators as you like.
You should also take into consideration the "on duplicate key" mechanisms of mysql.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
有效吗?是的。推荐吗?不。
die()
的问题是用户最终会看到失败的 SQL 查询,这是一个可怕的屏幕,除了少量文本之外什么也没有。这非常糟糕。相反,您应该以一种可以将完成失败传递给用户的方式处理这些错误:
事实上,还建议查看 set_error_handler,它可以让您捕获致命的 PHP 错误,而不是显示可能暴露您的 php 路径的可怕错误,如下所示:
你可以将它们发送到一般错误页面,这看起来更专业。
Is it valid? Yes. Is it recommended? No.
The problem with
die()
-ing from failed SQL query is what the user ends up seeing, which is a horrible screen with potentially nothing but a small amount of text. That's very bad.Instead, you should be handling these errors in a way that you can pass on the failure of completion to the user:
In fact, it's also recommended to take a look into set_error_handler, which lets you capture fatal PHP errors and instead of showing horrible errors that potentially exposure your php path like this:
You can send them to a general error page, which looks a lot more professional.
您可能想研究一下 mysql 替换语法
You might want to look into the mysql replace into syntax