|
Posted by Jerry Stuckle on 07/28/07 11:47
João Morais wrote:
> Hi there guys,
>
> My doubt is related to PHP and MySQL usage, and it's related to check
> if performed queries are performed with success, since we know that:
>
> [quote]
> mysql_query() - Return Values:
> For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
> resultset, mysql_query() returns a resource on success, or FALSE on
> error.
> For other type of SQL statements, UPDATE, DELETE, DROP, etc,
> mysql_query() returns TRUE on success or FALSE on error.
> [/quote]
>
> Each time we perform an sql query, we can check if it was performed
> with success like this:
>
> [code=php]
> $result = mysql_query('sql query string');
> if (!$result) echo mysql_error();
> [/code]
>
> If it fails, it will display the succeeded error.
>
> Now that I gave an example, here are my doubts:
>
> 1. Should this procedure be done every time a query is done, or,
> should we assume that 'SELECT' queries are always done with success if
> sql syntax is correct?
>
Never assume a MySQL call (or a call to any other external resource) is
successful. And you shouldn't display the error message itself - it
exposes internals of your site to the user. Rather, give them a generic
message and log the real message.
> 2. If we have a lot of queries that depend on each other (See the next
> example), imagine that query1 and query2 are made with success, but
> query3 fails, I will have inconsistent data since, the update is made
> on query2, but no delete will be made on query3 since it fails.
> How can we avoid this?
>
Use Innodb and transactions.
> [code=php]
> $result1 = mysql_query('SELECT ...');
> if (!$result1) {
> echo mysql_error();
> exit(0);
> }
>
> $result2 = mysql_query('UPDATE ... with data supplied from $result1');
> if (!$result2) {
> echo mysql_error();
> exit(0);
> }
>
> $result3 = mysql_query('INSERT / UPDATE / DELETE ... with data
> supplied from $result1');
> if (!$result3) {
> echo mysql_error();
> exit(0);
> }
> [/code]
>
> Hope you guys can understand my examples, if not, I'll try to explain
> in a better way.
>
> Thanks for your attention and spent time on reading this.
>
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
Navigation:
[Reply to this message]
|