INSERT only if both colomns are not duplicate - php

DELETE FROM RelationsAuthors WHERE MainId = :MainId AND AuthorId NOT IN (:authorarray)
The above code will delete anything that is not in authorarry and where MainId equals a specific value.
After the deletion I would like to insert the values of authoarray into the database if they do not exist without getting any errors.
*with using foreach $_POST['AuthorId']:
INSERT INTO RelationsAuthors (Id,MainId,AuthorId) VALUES('',:MainId,:AuthorId)
However I would like to add to my code that I need to INSERT only WHERE (MainId = :MainId AND AuthorId = :AuthorID) does not exist. How can I do that?

First, create a unique index on the two fields so the database will prevent duplicates for you:
create unique index idx_RelationsAuthors_MainId_AuthorId on RelationsAuthors(MainId, AuthorId);
Then the insert will fail with an error if you have duplicates. You can have this error ignored in a few ways. My preferred way is:
INSERT INTO RelationsAuthors (MainId, AuthorId)
VALUES(:MainId, :AuthorId)
ON DUPLICATE KEY UPDATE MainId = VALUES(MainId);
This will specifically ignore duplicate key errors, but other problems will still generate an error (if appropriate). Note I removed the first column. I'm guessing from the syntax that it is an auto-incremented id, so you don't need to include it in the insert statement at all.

Related

how to check mysql for duplicates with php

I need a way to check a database if a word is in it already if so then it doesn't have to be pushed to the database if the word isn't in it yet then it has to be pushed into it.
It's a MYSQL database and I have to do it in PHP this is what I got so far.
$result = array_count_values(explode(" ", $filter));
arsort($result);
foreach ($result as $word => $frequency)
{
if (!in_array($word, [" ", ""]))
query("words", "INSERT INTO Woord (woord) VALUE (?)",[$word], false);
}
query("words" "SELECT WHERE")
You have 2 options:
REPLACE
REPLACE INTO table
SET column = 'example'
This will overwrite if the record exists and if not it will create it.
INSERT IGNORE
INSERT IGNORE INTO table
SET column = 'example'
This will ignore the query if already exists and if not it will create it.
Your php query should look like this:
"INSERT IGNORE INTO ID142118_ascii.Woord (woord) VALUES (".$word.")"
put a unique constraint on the column "woord" in the table.
Then you can let your php script insert as many duplicate words as you want to, it will simply fail.
you could either add a part "ignore duplicate" in your query or just ignore the error you will get.
I thinks that will be easiest to do.
edit:
btw I can think of a lot of words containing serveral of the character you are stripping: "foto's", "zee-eend" etc
--
how to make a unique index:
ALTER TABLE asciiwoorden
ADD UNIQUE INDEX somename (Woord);

ON DUPLICATE KEY UPDATE - Condition WHERE vs CASE WHEN vs IF?

I am refering to this post. I am stuck with a problem I can't resolve. I try to insert multiple rows with a php script into a MySQL database. I don't succeed in updating the whole thing using ON DUPLICATE KEY UPDATE and using a WHERE condition (at the end of the code below) I would like to use to update only an entry has been modified recently:
// for information (used in a foreach loop):
$args[] = '("'.$row['lastname'].'", '.$row['phone'].', "'.$row['lastModification'].'")';
// then:
$stringImplode = implode(',', $args);
// Where I am stuck - WHERE statement:
$sql = $mysqli->query('INSERT INTO table_name '. (lastname, phone, timestamp) .' VALUES '.$stringImplode .'ON DUPLICATE KEY UPDATE lastname=VALUES(lastname), phone=VALUES(phone) WHERE timestamp > VALUES(lastModification);
Everything works fine except I cannot set any WHERE condition at this point that involves multiples entries. Maybe the WHERE statement in this case is not intended to refer to a condition in this statement.
I was told to try with a database procedure using a JOIN statement and a temporary table with first all my entries and then querying some conditions. But I have to admit I don't understand very well how I could leverage such a table to update an other table.
Is there an easy and lovely way to use a "CASE WHEN" or an "IF" statement in this case?
Would something like
INSERT INTO ... ON KEY DUPLICATE UPDATE lastname = VALUES(lastname), phone = VALUES(phone)
CASE WHEN (timestamp > VALUES(lastModification)) THEN do nothing ...
or
...ON KEY DUPLICATE UPDATE... IF (timestamp > VALUES(lastModification)) ...
If anyone could help me, I would be very grateful.
EDIT: Since I will have many variables, could it be used in this way:
INSERT INTO ... ON KEY DUPLICATE UPDATE
IF(timestamp > VALUES(timestamp),
(
name = VALUES(name),
number = VALUES(number),
timestamp = VALUES(timestamp)
....many other variables
),
(
name = name,
number = number,
timestamp = timestamp
....many other variables)
)
You can use simple IF function in value like this:
INSERT INTO ... ON KEY DUPLICATE UPDATE
name = VALUES(name),
number = VALUES(number),
timestamp = IF(timestamp > VALUES(timestamp), VALUES(timestamp), timestamp)
If condition is not met, it will update timestamp with the same timestamp which already exists. It does not matter, because update to same values is optimized before it is even executed, so MySQL will not make real update. You should not afraid of some performance penalty.
EDIT:
IF works likes this:
IF(condition, returned when true, returned when false)
Maybe you need to switch those two arguments to fit your condition like you want.

php incrementing while loop

$blanknumber = $_POST["blankstartnumber"];
while ($blanknumber <= ($_POST["blankendnumber"] ))
{
echo "$blanknumber";
$blankid = $blanknumber;
$query = "INSERT INTO blank (Blank_ID) VALUES ('$blankid')";
mysql_query($query,$con);
$blanknumber++;
}
So the values are added into the database. Lets say if I have the starting number at 1 and ending at 5. It will all the those values, but it's still trying to add more into the database. I also tried adding an IF statement aswell. if ($blanknumber != $_POST["blankendnumber"])
12345 Error: Duplicate entry '5' for
key 'PRIMARY'
Make sure your $POST value is an integer; by default, I believe it will be cast as a string.
$_POST['varName'] = (int) $_POST['varName'];
edit:
$blanknumber = $_POST["blankstartnumber"];
while ($blanknumber <= ($_POST["blankendnumber"] ))
This should only execute once, since you're setting both comparison variables equal. Definitely 2x check your code.
The database error indicates that Blank_ID is your primary key for that table, and you'd already inserted a 5 into the row. A primary key's values can exist only once in the entire table - duplicates are forbidden (if they were allowed, it wouldn't be a primary key anymore).
If your while loop isn't ending, I'd suggest dumping out both the blankendnumber and blankstartnumber before the loop starts, making sure you've got the right values in there.
It looks like it's actually functioning properly, but you might not have tidy'ed up your db table prior to running. If your output was:
123455 Error: Duplicate entry '5'...
Then, you'd have a programming error, as 5 is getting run twice. Instead, I think you already have data in the blank table that causes a conflict.
Edit: to automatically have MySQL handle the duplicate key error gracefully, you can use the ON DUPLICATE KEY clause to update the row.
INSERT INTO blank (Blank_ID) VALUES (5) ON DUPLICATE KEY UPDATE mod_date = NOW();

How do I delete everything from a table, except 1 entry in MySQL?

So I have an import/export module for OpenCart, but it's wiping the entire product option table before inserting new data...
I need to develop support for the 3rd party product options module I have, but in the meantime--I figure I'd just stop it from deleting an important column in my product options table.
In the product_option_value table, I have 'product_option,' 'product_id,' 'quantity' etc., and there's one column named 'info' that I want to NOT wipe. The method is below:
function storeOptionsIntoDatabase( &$database, &$options )
{
// find the default language id
$languageId = $this->getDefaultLanguageId($database);
// start transaction, remove options
$sql = "START TRANSACTION;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option`;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option_description` WHERE language_id=$languageId;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option_value`;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option_value_description` WHERE language_id=$languageId;\n";
$this->import( $database, $sql );
...more code...
}
I'm not that familiar with MySQL, but I want something to the effect of:
$sql .= "DELETE FROM `".DB_PREFIX."product_option_value` WHERE column != 'info';\n";
Thanks!
Edit:
I tried Michael's suggestion to use UPDATE and explicitly setting them all to NULL... but that returned this error:
Error: Duplicate entry '0' for key 1
Error No: 1062 UPDATE
oc_product_option_value SET
product_option_value_id=NULL,
product_option_id=NULL,
product_id=NULL, quantity=NULL,
subtract=NULL, price=NULL,
prefix=NULL, sort_order=NULL,
weight=NULL, sku=NULL, image=NULL
I tried taking out the primary key:
$sql .= "UPDATE
".DB_PREFIX."product_option_value
SET product_option_id=NULL,
product_id=NULL, quantity=NULL,
subtract=NULL, price=NULL,
prefix=NULL, sort_order=NULL,
weight=NULL;\n";
but I get:
Error: Duplicate entry '1' for key 1
Error No: 1062 INSERT INTO
`oc_product....
Edit:
Okay, so I removed the 'primary_key' field from the INSERT... and I got no error messages from the upload. But when I view a product that product options, I get this message the top of my page:
Notice: Undefined index: name in
/httpdocs/ocart/catalog/model/catalog/product.php
on line 418Notice: Undefined index:
name in
/httpdocs/ocart/catalog/model/catalog/product.php
on line 418Notic.... it repeats
Make sure I understand: You want to clear values from all columns in the table product_option_value except for the column info ? If that's what you want, then the following may work. Please don't run it before we're clear on what you're trying to do!
DELETE FROM syntax implies deleting from a table name, not a column name. What you'll need to do instead is to UPDATE your rows to set all columns except the one you intend to keep to be either NULL or empty or their default value.
Don't forget to add a WHERE condition if you need to keep some rows as they are without modifying them! Without a WHERE, this query will NULL out all columns specified in the whole table.
UPDATE product_option_value
SET
product_option = NULL,
product_id = NULL,
quantity = NULL,
etc...
WHERE (some where condition if you need one)
I'm adding a second answer, taking a completely different approach which avoids SQL problems.
Export your table as a comma-separated text file. You can do this with phpmyadmin, or MySQL Workbench.
Open your CSV in a spreadsheet
Clear out the columns you want to clear out.
Save as a new CSV
Import the CSV back into your database using phpmyadmin, Workbench, or the LOAD DATA LOCAL INFILE syntax.

Update a row if ID exists else Insert

This is the code of a .php file. The column "memberid" has a unique index. When a user enters a record with an existing memberid, the record must get updated else a new row is created.
I also want to show an alert box. For test purposes I added like the way below, but it is not firing. No message is displayed.
I also want to know whether it is the right approach to handle insert/update automatically?
<META http-equiv="refresh" content="2; URL=socialprofile.html">
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once("../Lib/dbaccess.php");
//Retrieve values from Input Form
$CandidateID = $_POST["inCandidate"];
$SocialProfile = $_POST["inActivities"];
$InsertQuery = "INSERT INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";
$UpdateQuery = "UPDATE candidate_db_social SET socialactivities='".$SocialProfile."', lastupdated=now() WHERE memberid=".$CandidateID;
try
{
$Result = dbaccess::InsertRecord($InsertQuery);
}
catch(exception $ex)
{
$Result = dbaccess::InsertRecord($UpdateQuery);
echo "<script type='text/javascript'>alert('".$ex."');</script>";
}
?>
You should use the MySQL ON DUPLICATE KEY clause:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Also see REPLACE:
http://dev.mysql.com/doc/refman/5.0/en/replace.html
See the MySQL REPLACE keyword. It works exactly like INSERT, but overwrites existing records based on primary key. Read up on the details though, because it's not exactly equivalent to trying an INSERT, followed by an UPDATE.
INSERT ... ON DUPLICATE might be what you need instead. Situations with triggers or foreign keys come to mind. Longer syntax however :)
REPLACE INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";
you can use the INSERT ... ON DUPLICATE KEY UPDATE syntax, as in:
insert into t values ('a', 'b', 'c') on duplicate key
update a='a', b='b', c='c'
use mysql
INSERT INTO table VALUES()
ON duplicate KEY UPDATE ..;
example :
http://www.mysqlperformanceblog.com/2006/05/29/insert-on-duplicate-key-update-and-summary-counters/
I usually just check for the existence of a record ID value from either the $_POST or $_GET array (depending on the situation). If a value exists and is numeric, attempt to UPDATE the row with the corresponding ID; if not perform an INSERT query.

Categories