MySQL update or insert or die query

天涯浪子 提交于 2019-12-24 10:12:58

问题


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');`

回答1:


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.




回答2:


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




回答3:


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:

$update_result = $db->query($update);
if(!$update_result) {
  // Yikes! Tell the user something went wrong!
  // Show them an error page or error message
}

$insert_result = db->query($insert);
if(!$insert_result) {
  // Yikes! Tell the user something went wrong!
  // Show them an error page or error message
}

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:

Fatal error: Cannot use assign-op operators with overloaded objects nor string offsets in /check/out/my/directory/structure/wp-admin/includes/file.php on line 688

You can send them to a general error page, which looks a lot more professional.




回答4:


You might want to look into the mysql replace into syntax



来源:https://stackoverflow.com/questions/6074557/mysql-update-or-insert-or-die-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!