Jump to content

Is there any better method to validate $result= mysql_query($q1);


sayedsohail

Recommended Posts

Hi everyone,

 

I am just wondering, if there is any better method to validate the mysql_query result, here is the code currently in use.

 

$result= mysql_query($q1);
if($result)
{
$outdata[]= "Record Updated Successfully ";  
}
else
{
if (mysql_errno($conn) == 1062)
{
$outdata[]= "Update failed, duplicate Entry, Already exist in database ";  
}
}

$result = mysql_query($q1);

 

if (mysql_affected_rows() == 1)

{

$outdata[]= "Record Updated Successfully ";

}

else

{

echo mysql_error();

}

 

If the query is only expected to update a single row, this is fine.  But what happens when the update works on more than one row?

The short answer to your question is you use mysql_affected_rows() just like with UPDATE.

 

The long answer is there is no clear cut way to determine if a query was successful as the definition of success varies.

 

For example, say you run an update query that can potentially update multiple rows.  All of the following could be considered successful depending on what you're doing:

 

* The query updated all of the rows expected

 

* The query updated some of the rows expected

 

* The query updated zero rows

 

The same is true with insert.

 

The best thing you could do is follow this link:

http://php.net/mysql

 

Scroll down to the area labeled Table of Contents; this is a list of all the mysql_* functions you can use in your program.  Read the names and the descriptions and look for code examples.

 

if (mysql_affected_rows() != 0)

mysql_affected_rows will return -1 if the previous query failed so this check can erroneously report success.

  // The most general way to test for success
  if(mysql_affected_rows() >= 0){
  }

if you are doing just one update then you can check mysql_insert_id() if its multiple updates this only returns the last update id (or the first - i have experienced this on the odd occasion! - don't ask me to replicate) so you'd have to do some magic before hand like count the current number of rows then insert then count the number afterwards - this would involve you locking the particular table so no other wriets could be performed before you've finished. [and breathe]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.