*simple* - Best way to make sure INSERT query worked

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

*simple* - Best way to make sure INSERT query worked

Post by Stryks »

I have a query running at the moment, and for the sake of trying to figure it out, I left it in the same format as a SELECT query that I got from an example somewhere along the line.

Code: Select all

$sql = "INSERT INTO `member_auth` (`ID`, `Username`, `Password`) VALUES ('', 'Test', 'test')";
if(!($result = mysql_query($sql))) die(mysql_error());
I guess what I am wondering is, is this going to catch any errors of data not being inserted into the database? I have looked around and people seem to just be going something like ...

Code: Select all

$sql = "INSERT INTO `member_auth` (`ID`, `Username`, `Password`) VALUES ('', 'Test', 'test')";
mysql_query($sql)
if (mysql_affected_rows() < 1) $Output .= '<li>Database Error!</li>';
Are they pretty much the same? Is one preferable to the other? Is there a better way?

Any help here would be great. Thanks
Unipus
Forum Contributor
Posts: 409
Joined: Tue Aug 26, 2003 2:06 pm
Location: Los Angeles, CA

Post by Unipus »

I like this format:

Code: Select all

$Query_Result = mysql_query($SQL_String) 
     or die (mysql_error() . "<p>" . $SQL_String);
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

PHP Manual wrote: A non-FALSE return value means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Weirdan - I hate to ask a silly question (but here goes), under what circumstance would an insert query be valid but effect no rows?

And I guess what you are saying is .. well .. that both should be used? Or that just checking for the affected rows will tell me if it was a valid query?

Thanks
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Use the both and you'll be safe ;)
My thought was that if the insert fails because of key constraints it would still return true because it has the right syntax. I was wrong.
Post Reply