Jaw Ali
Jaw Ali

Reputation: 205

Insert data only if record does not exist

I want to insert data in a table only if the record with a given CatalogID does not exist.

 $userId = $_POST['userId'];
 $catalogID = $_POST['catalogID'];
 $content_AddedTime = $_POST['content_AddedTime'];

 $query = ("INSERT INTO LibraryMaster (UserID,CatalogID,ContentAddedDateTime)
      VALUES ('$userId','$catalogID','$content_AddedTime')");
 mysql_query($query,$con);
 printf("Records inserted: %d\n", mysql_affected_rows());
 echo($user_Name)

Upvotes: 0

Views: 791

Answers (3)

geeksal
geeksal

Reputation: 5016

$query="INSERT INTO LibraryMaster (UserID,CatalogID,ContentAddedDateTime)
SELECT * FROM (SELECT '".$userId."', '".$catalogID."', '".$content_AddedTime."') AS tmp
WHERE NOT EXISTS (
  SELECT CatalogID FROM LibraryMaster WHERE CatalogID = '".$catalogID."t'
 ) LIMIT 1";

Upvotes: 0

Desire
Desire

Reputation: 1

You could use this sort of function

public function Checkrecord($catalogID )
    {
        $query="Select * from table_name where catalog_id=$catalogID ";
                  mysql_query($query,$con);
        if(mysql_num_rows($query)>0)
        {
            //report error
        }
        else
        {
            //insertQuery
        }
    }

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Create a UNIQUE index on CatalogID.

Upvotes: 2

Related Questions