Jump to content


Photo

Evaluating Select Results Using Php?


  • Please log in to reply
4 replies to this topic

#1 tomjones

tomjones
  • Members
  • PipPip
  • Member
  • 12 posts

Posted 28 June 2006 - 05:41 PM

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:

$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";
   }

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:

$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);


Any advice on this would be appreciated. I've also researched WHERE NOT EXISTS but was unable to achieve it this way either.

Thanks..


#2 Orio

Orio
  • Staff Alumni
  • Advanced Member
  • 2,491 posts

Posted 28 June 2006 - 05:44 PM

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.
Think you're smarty?

(Gone until 20 to November)

#3 tomjones

tomjones
  • Members
  • PipPip
  • Member
  • 12 posts

Posted 28 June 2006 - 05:56 PM

Thanks for pointing that out, i've fixed the operator but the statement does still not evaluate properly.

#4 Orio

Orio
  • Staff Alumni
  • Advanced Member
  • 2,491 posts

Posted 28 June 2006 - 06:36 PM

Use this:

$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...

Orio.
Think you're smarty?

(Gone until 20 to November)

#5 tomjones

tomjones
  • Members
  • PipPip
  • Member
  • 12 posts

Posted 28 June 2006 - 07:15 PM

Thanks.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users