tomjones Posted June 28, 2006 Share Posted June 28, 2006 Hi, I do not understand how to evaluate the results of a SELECT statement using php.I'm using php 4 and a mysql 5 database.I've assigned the select statement to a variable, however i need to know if the query returned any results, and run a mysql INSERT statement if the SELECT query did not return results.Below is the syntax i am using: [code]$query = mysql_query("SELECT * FROM $table WHERE Field = '$field'"); $num_rows = mysql_num_rows($query); return $num_rows; if($num_rows = 0) { $query_fail = @mysql_query("INSERT INTO $anothertable (Field) VALUES " . "('$field')"); return "error=" . mysql_error(); } else { return "user=ok"; }[/code]When testing i noticed if i moved the mysql_num_rows below the 2nd query It executed regardless of any if statement.I believe this was the syntax: [code]$query = mysql_query("SELECT * FROM $table WHERE Field = '$field'"); if(!query) { $query_fail = @mysql_query("INSERT INTO $anothertable (Field) VALUES " . "('$field')"); return "error=" . mysql_error(); } else { return "user=ok"; } mysql_num_rows($query);[/code]Any advice on this would be appreciated. I've also researched WHERE NOT EXISTS but was unable to achieve it this way either.Thanks.. Quote Link to comment Share on other sites More sharing options...
Orio Posted June 28, 2006 Share Posted June 28, 2006 I think your problem is here:if($num_rows = 0)It should be:if($num_rows [!--coloro:#FF0000--][span style=\"color:#FF0000\"][!--/coloro--]==[!--colorc--][/span][!--/colorc--] 0)Orio. Quote Link to comment Share on other sites More sharing options...
tomjones Posted June 28, 2006 Author Share Posted June 28, 2006 Thanks for pointing that out, i've fixed the operator but the statement does still not evaluate properly. Quote Link to comment Share on other sites More sharing options...
Orio Posted June 28, 2006 Share Posted June 28, 2006 Use this:[code]$query = mysql_query("SELECT * FROM $table WHERE Field = '$field'");$num_rows = mysql_num_rows($query);if($num_rows =- 0){$query2="INSERT INTO $anothertable (Field) VALUES ('$field')";$query_fail = @mysql_query($query2); if(strlen(mysql_error())>0){die(mysql_error());};};//continue code...[/code]Orio. Quote Link to comment Share on other sites More sharing options...
tomjones Posted June 28, 2006 Author Share Posted June 28, 2006 Thanks. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.