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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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