Page 1 of 1

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

Posted: Tue Feb 03, 2004 7:31 pm
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

Posted: Tue Feb 03, 2004 7:36 pm
by Unipus
I like this format:

Code: Select all

$Query_Result = mysql_query($SQL_String) 
     or die (mysql_error() . "<p>" . $SQL_String);

Posted: Tue Feb 03, 2004 7:38 pm
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.

Posted: Tue Feb 03, 2004 7:52 pm
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

Posted: Tue Feb 03, 2004 8:10 pm
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.