Jump to content

INSERT into db when record does not excist


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 post
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 post
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 post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...