Jump to content

Archived

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

tomjones

Evaluating Select Results Using Php?

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Thanks for pointing that out, i've fixed the operator but the statement does still not evaluate properly.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

×

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.