Jump to content

Evaluating Select Results Using Php?


tomjones

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..
Link to comment
https://forums.phpfreaks.com/topic/13132-evaluating-select-results-using-php/
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.

Archived

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

×
×
  • Create New...

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.