0

I've just started with php, and i wondered if anyone can help. i have this

$sql="INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);

I need to know how to make it see if the event exists, and if it does i need it to do nothing, if it doesn't then insert it!

Sumit Bijvani
  • 7,762
  • 17
  • 46
  • 79
user2618262
  • 71
  • 1
  • 6

3 Answers3

0

split it into 2 queries:

1) check if event exists. If yes then do nothing, else insert a new event

2) continue with your query. this way the event will allays exist when inserting your data

Ivan Bacher
  • 4,687
  • 8
  • 30
  • 49
0

Try:

$query = mysql_query("SELECT $myevent from $tbl_name ")
$rows = mysql_num_rows($query)

if ($num_rows > 0) {
  // do nothing
}
else {
  $sql = "INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
  $result = mysql_query($sql);
}

As a sidenote: mysql_ functions are deprecated and it's recommended to switch to mysqli or PDO.

Amal Murali
  • 70,371
  • 17
  • 120
  • 139
  • `ON DUPLICATE KEY UPDATE` is used when you want to change a value when there is a duplicate key that is found. The question states that he wants it to do nothing. `INSERT IGNORE` is the proper MySQL syntax in this scenario. Additionally, `ON DUPLICATE KEY UPDATE` requires an expression to follow it to my understanding for specifying what columns to update when the condition is satisfied. – wes.hysell Jul 25 '13 at 10:59
0

This is something that can be done through MySQL alone.

Setup a unique key for the event column by running the following MySQL Command on your table:

CREATE UNIQUE INDEX `i_event` ON `TABLE_NAME_GOES_HERE` (`event`);

For more information: http://dev.mysql.com/doc/refman/5.0/en/create-index.html

Do this for every possible table you expect to see in the $tbl_name variable.

Then, change your PHP Query:

$sql="INSERT IGNORE INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);

For more information on INSERT IGNORE: http://dev.mysql.com/doc/refman/5.5/en/insert.html

INSERT IGNORE simply does as it states... it will try to insert the row unless it fails validation (in this case from an index that you declared HAS to be unique).

wes.hysell
  • 1,099
  • 9
  • 14