Jump to content

INSERT into db when record does not excist


Luc

Recommended Posts

Hey guys,

I have a problem. I want to write a record in my db when it does not already exists. For this, i have been looking on the web and found multiple solutions on Stackoverflow. The one I use is proved working, by the stack user however I get my die response :(.

I use the following query (mysql/php):

$query= "IF NOT EXISTS (SELECT * FROM tasksmade WHERE teamnumber='$teamnumber' AND tasknumber='$tasknumber' AND date='$date')
    INSERT INTO tasksmade (teamnumber, tasknumber, taskfinished, date) 
    VALUES ('$teamnumber', '$tasknumber', '$taskfinished', '$date')";    
 
$result= mysql_query($query,$mysql) or die("The query result has failed on the db!");

Hope someone can help!

Thanks!

 

Link to comment
Share on other sites

If you set a unique index on teamnumber, tasknumber, and date, then you can use INSERT IGNORE to insert a new record as long as it doesn't violate the unique index (i.e., as long as it's not already there).  You can also use INSERT .. ON DUPLICATE KEY UPDATE to either insert a new row or update an existing row if it already exists.

Link to comment
Share on other sites

You should stop using the mysql library, it's been deprecated for over a decade for security reasons. Every manual page for mysql_ functions has a large warning on them: http://php.net/mysql_query

You should not put variables right in your SQL string, that leaves your code open to being hacked. Use prepared statements, W3Schools had a tutorial page about them: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...