Luc Posted April 19, 2017 Share Posted April 19, 2017 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 More sharing options...
dsonesuk Posted April 19, 2017 Share Posted April 19, 2017 That looks more like MSSQL rather than MYSQL, can't you check number of records returned, if 0 insert. Link to comment Share on other sites More sharing options...
Luc Posted April 19, 2017 Author Share Posted April 19, 2017 Ah, that might be the reason why I get the error.... How would you do this? Link to comment Share on other sites More sharing options...
justsomeguy Posted April 19, 2017 Share Posted April 19, 2017 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 More sharing options...
Luc Posted April 20, 2017 Author Share Posted April 20, 2017 Thanks guys, just implemented it and it works like a charm Link to comment Share on other sites More sharing options...
Ingolme Posted April 20, 2017 Share Posted April 20, 2017 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 More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now