开发者

Should you always end mysql queries with "or die?"

Example queries in some tutorials ALWAYS end with:

or die(mysql_error());开发者_开发技巧  

I can see why you would would sometimes want to do this, but they even use this for queries that really shouldn't cause a problem. Is it a good practice to always use this, or are they just doing it to help you debug as you learn?


NO.

Avoid that at all cost!

  1. It's a horrible message to show an end user
  2. mysql_error may expose information you don't want to be given
  3. There is no way to handle the error, i.e revert.

Imagine a database of transactions - your customer sends money, so you have to modify two tables (two queries).

First one transfers money from X to Y and succeeds. The second one has to subtract Y from X fails.

You have no way to revert the transaction and the error is not logged. Effectively making user Y happy and X left confuse where the money went...

Use a sensible error handling for queries - either make a class that will handle that for you or use ORM.


It depends on what you mean by "shouldn't be a problem".

If you mean "well it won't fail", what happens if the database server goes offline?

Only if you mean "It doesn't matter whether it fails or not, the script can keep running without a problem" that you should consider not having the or die there.


The word "shouldn't" is bad here. Queries that shouldn't have a problem can still be affected by external factors, e.g. connection to the database going down.


but they even use this for queries that really shouldn't cause a problem

Even the simplest SELECT * FROM FOO can cause a problem if the network between the web server and the database server falls over. It's good practice because when dealing with external systems such as databases, you really can't ever assume that something is 'safe'.

In production code, you may not wish to use die() to handle errors - you could perhaps run some custom code to deal with it. At any rate, you should definitely handle the error in one way or another, and die() is a good way to start.


You don't necessarily need

or die()

But you should have some kind of error handling system. If you don't have one in place yet, I would add it to my queries, even the simple ones.

EDIT: To clarify, by "it" I mean the or die() statement.


I was thinking that it wouldn't hurt to use it towards the top of your pages where ever you're database connection information would be, Use it when trying to connect to the database only.

But why us it on every query you perform! Obviously if it connected to the database then if you know No other errors should occur then i wouldn't see why you couldn't avoid using it more than Once Per Page!!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜