• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 564
  • Last Modified:

MySQL - insert rows into table where no matches found in column?

Hi,
I want to insert new rows into my table, but only if the icon_name does not already exist.
What is the best way to do this?

Thanks in advance for your help.

INSERT INTO `icons` (`icon_name`) VALUES ('page one');
INSERT INTO `icons` (`icon_name`) VALUES ('help page');
INSERT INTO `icons` (`icon_name`) VALUES ('another page');



CREATE TABLE IF NOT EXISTS `icons` (
  `id` tinyint(3) NOT NULL auto_increment,
  `icon_position` tinyint(3) default '100',
  `icon_name` varchar(120) NOT NULL,
  `visible` enum('1','0') default '1',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

--
-- Dumping data for table `icons`
--

INSERT INTO `icons` (`id`, `icon_position`, `icon_name`, `visible`) VALUES
(1, 0, 'was one', '1'),
(2, 4, 'help page', '1'),
(3, 1, 'was three', '0'),
(11, 100, 'new_webpage', '1');
0
sabecs
Asked:
sabecs
3 Solutions
 
Walter RitzelSenior Software EngineerCommented:
just add a unique constraint in the icon name column
0
 
Jagadishwor DulalBraces MediaCommented:
OK so you want to insert icon_name which should not be already exist. You must check first is there any name exist or not like:

$result = mysql_query("SELECT * FROM icons WHERE icon_name='$icon_name'");
if(mysql_num_rows($result)>0){
	echo "Icon name Already Exist. Can not add Icon";
	exit;
}else{
//Write your insert query here.

  }

Open in new window


0
 
Aaron TomoskyTechnology ConsultantCommented:
If there is a unique constraint you just use insert ignore
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
Walter RitzelSenior Software EngineerCommented:
just to complement, here is the example script:
create table t1 (
 f1 integer primary key,
 f2 varchar(50) unique not null
)
0
 
Mohamed AbowardaSoftware EngineerCommented:
Add PRIMARY_KEY to the table field:
http://www.w3schools.com/sql/sql_primarykey.asp
0
 
sabecsAuthor Commented:
Thanks for your help.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now