Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 996
Brien Avatar asked Jan 25 '10 03:01

Brien


People also ask

Is mysql_ query DEprecated?

This extension was deprecated in PHP 5.5. 0, and it was removed in PHP 7.0.

How long should a MySQL query take?

A query can take up to one hour if it crunches extremely large amount of data once every 6 months in a system where only it is running. It won't be a problem. Another query can take 100ms only but it's on a web server and 1000 persons are connecting simultaneously!

What is mysql_ query?

mysql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mysql_connect() was called with no arguments, and use it.

Why use mysql_ query in PHP?

Definition and Usage. The mysql_query() function executes a query on a MySQL database. This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.


1 Answers

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.

like image 117
LiraNuna Avatar answered Oct 19 '22 23:10

LiraNuna