Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert unique values from PHP array into SQL table [duplicate]

Tags:

sql

php

insert

Possible Duplicate:
How to 'insert if not exists' in MySQL?

There is SQL table:

CREATE TABLE IF NOT EXISTS `MyTable` (
  `id` smallint(6) NOT NULL AUTO_INCREMENT,
  `MyVar` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`id`)
) 

And there are two PHP arrays arr1[]=array("abc","bcd") and arr2[]=array("abc","cde").

Let's say I have saved arr1[] values to SQL table. Now let's suppose I need to save arr2[] values to the same SQL table. Which SQL INSERT query do I need to write in order to avoid duplicate saving of "abc" entry? The result must be:

MyTable:
1  |  abc
2  |  bcd
3  |  cde

but NOT:

MyTable:
1  |  abc
2  |  bcd
3  |  abc
4  |  cde

UPDATE: Maybe the MyTable should be created/defined in such a way that duplicate entries are ignored?

like image 747
You Kuper Avatar asked Aug 29 '12 11:08

You Kuper


People also ask

How to INSERT unique values in MySQL using php?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

How to unique array in php?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);

How do you insert unique rows in SQL?

INSERT DISTINCT Records INTO New Tables In order to copy data from an existing table to a new one, you can use the "INSERT INTO SELECT DISTINCT" pattern. After "INSERT INTO", you specify the target table's name - organizations in the below case.


2 Answers

There are 3 possible solutions: using INSERT IGNORE, REPLACE, or INSERT ... ON DUPLICATE KEY UPDATE. Check this article.

You can also in memory intersect array-s and then insert just unique values if that solution fits for you.

like image 120
Krešimir Lukin Avatar answered Nov 01 '22 18:11

Krešimir Lukin


Make the MyVar as UNIQUE in your table.

Like this:

CREATE TABLE IF NOT EXISTS `MyTable` (
  `id` smallint(6) NOT NULL AUTO_INCREMENT,
  `MyVar` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `myvaridx` (`MyVar`)
);

or, if you're unable to recreate the table, alter it using

ALTER TABLE `request`
ADD UNIQUE INDEX `myvaridx` (`MyVar`)
like image 42
hjpotter92 Avatar answered Nov 01 '22 18:11

hjpotter92