I'm reading and store rss feed in my database ,my requirement is if link field is same then update title and description only in database.
I'm using ON DUPLICATE KEY UPDATE but after entered query.its insert only a single data in database and failed and show a error
my code is
<?php
include_once 'db.php';
$homepage = file_get_contents('http://rss.cnn.com/rss/edition_us.rss');
$movies = new SimpleXMLElement($homepage);
foreach($movies->channel->item as $opt){
$title= $opt->title;
$tittle=mysql_real_escape_string($title);
$link=$opt->link;
$links=mysql_real_escape_string($link);
$des=$opt->description;
$dess=mysql_real_escape_string($des);
"INSERT INTO store_feed (title, link, description) VALUES ('$tittle','$links','$dess')";
$sql="ON DUPLICATE KEY UPDATE title= '$tittle',description='$dess'";
$result=mysql_query($sql) or die( mysql_error() );
}
?>
and table structure is:-
CREATE TABLE `test_om`.`store_feed` (
`id` INT NOT NULL AUTO_INCREMENT ,
`title` VARCHAR( 200 ) NOT NULL ,
`link` VARCHAR( 200 ) NOT NULL ,
`description` VARCHAR( 500 ) NOT NULL ,
`feedburner` VARCHAR( 200 ) NOT NULL ,
PRIMARY KEY ( `id` ) ,
UNIQUE (
UNIQUE KEY `link` (`link`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and error is
Duplicate entry 'http://rss.cnn.com/~r/rss/edition_us/~3/Wl1V4JsNqDU/index.html' for key 'link'
I have done some changes in my query ,short it.
<?php
include_once 'db.php';//config file
$homepage = file_get_contents('http://rss.cnn.com/rss/edition_us.rss');//link of rss feed page
$movies = new SimpleXMLElement($homepage);
foreach($movies->channel->item as $opt){
$sql="INSERT INTO store_feed SET `title` = '".mysql_real_escape_string($opt- >title)."',
`link`='".mysql_real_escape_string($opt->link)."',
`description`='".mysql_real_escape_string($opt->description)."'"
."ON DUPLICATE KEY UPDATE `title`='".mysql_real_escape_string($opt->title).
"',`description`='".mysql_real_escape_string($opt->description)."'";
$result=mysql_query($sql) or die( mysql_error() );
}
?>
and its solve my problem....
INSERT ... ON DUPLICATE has to be one query:
$sql="INSERT INTO store_feed (title, link, description) VALUES ('$tittle','$links','$dess')"
." ON DUPLICATE KEY UPDATE title= '$tittle',description='$dess'";
$result=mysql_query($sql) or die( mysql_error() );
You forgot to update the link field which causes the conflict.
Related
I am trying to make a INSERT by UNIQUE and I am getting stuck, What I want too know is how I would do is make it so Column A is ALWAYS UNIQUE unless Column C has two different values and then it will insert into the database a second row for Column A where Column C is different.
a|b|c
-----
1|2|3
2|4|5
1|6|7
So I am currently using this sql table
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL UNIQUE,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
With this query
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
It inserts the way I want so there is only 1 of each SteamID but it also will not insert if the same SteamID has two values for position.
EDIT:
What I have is a xml file I load up and insert data into the database based on the data in the xml file, What I need is below.
$xml = simplexml_load_file("players.xml");
foreach($xml->children() as $player)
{
$id = $player->attributes()->id;
$profile = new SteamProfile($id);
$name = mysql_real_escape_string($profile->getUsername());
$lastlogin = $player->attributes()->lastlogin;
$position = $player->lpblock->attributes()->pos;
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
so the xml file gets read and then the data in the file gets inserted into the database. sometimes the xml file would contain
<player id="76561197961716203" lastlogin="8/22/2014 10:49:28 PM">
<acl id="76561197961543041"/>
<acl id="76561197988417990"/>
<lpblock pos="273,93,-102"/>
<lpblock pos="1322,62,-1711"/>
</player>
at which point I would need a second row created for the second <lpblock pos=
So its currently inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
and it should be inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
|61|SwordFish |76561197961716203|1322,62,-1711|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
I'm not sure what you are trying to achieve, but you can set a UNIQUE restraint on a combination of columns, in your case SteamID and position:
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_combination_of_two_fields` (`SteamID`,`position`)
) ENGINE=InnoDB;
Thanks for you help Jeroen I did this and its working.
foreach($player->children() as $lpblock)
{
$position = $lpblock->attributes()->pos;
if(!empty($position))
{
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
}
However I would like all of the SteamID's inserted and not just the ones with a $position set. When I take this out and try it adds the correct rows but also adds another row with a blank $position as if there is a SteamID that's blank when there is none.
if(!empty($position)){
}
I have table definitions:
create table users(
id int not null auto_increment,
usernaname varchar(50) not null,
pass varchar(50) not null,
primary key(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table users_description(
user_id int not null,
description varchar(255),
key(user_id),
foreign key(user_id) references users(id) on delete cascade
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and it is good, works nice.
but when I add a new user I use a next query:
insert into users (username, pass) values('test', 'test');
but how to add a id of user automatically in users_description table?
Something similar to to this:
insert into users_description values(
select id from users where username = 'test',
'user description');
I want to use only two queries, is this possible?
You can use LAST_INSERT_ID() to get the last inserted primary key id (which would be from the users table):
INSERT INTO users_description VALUES
(LAST_INSERT_ID(), 'test', 'user description');
$query = mysql_query("insert form (username, pass) values('test', 'test')");
$id = mysql_insert_id();
gives you the last inserted id in PHP ..
Use LAST_INSERT_ID(). Example here.
My problem in mysql.
My Table name is categories.
CREATE TABLE IF NOT EXISTS `categories` (
`cid` int(10) NOT NULL AUTO_INCREMENT,
`category_name` char(100) DEFAULT NULL,
`parent` int(10) DEFAULT NULL,
PRIMARY KEY (`cid`),
UNIQUE KEY `parent` (`parent`,`category_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
parent and category_name are unique fields.
If the record not exists I would like to run insert into command.;
select last_insert_id() #get last insert id.
UPDATE
MY PHP Code is:
$sql = "insert into categories (parent,category_name) values ('".$field[parent]."','".$temp->cat_name."')";
if (#$db->query($sql)){
$cid = $db->get_var("select last_insert_id()");
}else{
$cid = $db->get_var("SELECT cid FROM categories WHERE parent=".$field[parent]." and category_name='".$temp->cat_name."'");
}
How can I get exist id return?
If the record not exists I would like to run insert into command.;
You can use INSERT IGNORE ....
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('A', 1); // will insert it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('A', 1); // will ignore it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('A', 2); // will insert it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('B', 2); // will insert it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('B', 2); // will ignore it
From the docs:
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.
select last_insert_id()
return a ID after the successful insert. for further processing you can store it in your database after a successful insert.
also you can use insert ignore into .... for avoid duplicate insert
I think this is the best way to do it:
$sql = "insert into categories (parent, category_name) values ('".$field[parent]."','".$temp->cat_name."') ON DUPLICATE KEY UPDATE cid=LAST_INSERT_ID(cid)";
$db->query($sql);
$cid = $db->insert_id;
var_dump($cid);
I'm reading and store a RSS feed in my database.I'm using this code
<?php
include_once 'db.php';
$homepage = file_get_contents('http://rss.cnn.com/rss/edition_us.rss');
$movies = new SimpleXMLElement($homepage);
foreach($movies->channel->item as $opt){
$title= $opt->title;
$tittle=mysql_real_escape_string($title);
$link=$opt->link;
$links=mysql_real_escape_string($link);
$des=$opt->description;
$dess=mysql_real_escape_string($des);
$sql="INSERT INTO store_feed (title, link, description)
VALUES ('$tittle','$links','$dess')";
$result=mysql_query($sql) or die('Error, insert query failed');
}
?>
and table structure is
Table structure for table store_feed
CREATE TABLE IF NOT EXISTS `store_feed` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL,
`link` varchar(200) NOT NULL,
`description` varchar(500) NOT NULL,
`feedburner` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
now my requirement is when insert a new record if link is same then update only title and description of this field without insert record again.
in other word I want to stop duplicate data if link is same.
Usually, I do something like this:
WARNING: UNTESTED CODE!
$sql = "SELECT id FROM store_feed WHERE link = '$links' LIMIT 1";
$rs = mysql_query($sql) or die( mysql_error() );
if( mysql_num_rows($rs) > 0)//we got link
{
$r = mysql_fetch_array($rs);
$id = $r['id'];
$sql = "UPDATE store_feed SET title = '$title', description = '$dess' WHERE id = '$id'";
mysql_query($sql) or die( mysql_error() );
} else {
$sql = "INSERT INTO store_feed (title, link, description) VALUES ('$tittle','$links','$dess')";
mysql_query($sql) or die( mysql_error() );
}
Before you inserting every feed into database just check title and description exist in database if not exist insert that row into database.
http://www.exceptionhandle.com
Got three tables (blogs, tags, and blogtags) all AI and ID set to primary key. I'm making a tagging system to keep track of my sites (localhost). The code below is sort of working, but mysql_insert_id just doesn't seem reliable enough since I get some duplicate rows and the occasional 0 value in it.
/// inserts the blog into blog table.
$insert = mysql_query("INSERT INTO blogs (id, url, user, pass, dname, islocal, cat2post) VALUES ('', '$blog', '$bloguser', '$blogpassword', '','NO','$_POST[cat2blog]')")or die( 'Error: ' . mysql_error());
$taggit1 = mysql_insert_id();
$page->content .= "<p class=\"alert\">Success - External blog Added!</p>";
/// let's see what tags we have and explode them.
//$tags = $_POST['tags'] which is an array of words seperated by comma
$tags = 'fishing';
$pieces = explode(",", $tags);
/// go through the tags and add to tags table if needed.
foreach ($pieces as $l){
$l = trim($l);
$query = "SELECT id FROM tags WHERE tag = '$l'";
$result = mysql_query($query) or die( "Error: " . mysql_error() . " in query $query");
$row = mysql_fetch_array($result);
$taggit2 = $row[0];
if ($taggit2 == '') {
$insert2 = mysql_query("INSERT INTO tags (id, tag) VALUES ('','$l')")or die( 'Error: ' . mysql_error());
$taggit2 = mysql_insert_id();
$page->content .= "<p class=\"alert\">This tag didn't exist - so I inserted a new tag</p>";
}
/// for each tag we have, let's insert the blogstags table so we can reference which blog goes to which tag. Blogstags_id should map to the id of the blog.
$insert3 = mysql_query("INSERT INTO blogstags (id, tag_id, blogstags_id) VALUES ('','$taggit2','$taggit1')")or die( 'Error: ' . mysql_error());
}
Guess I need a different solution than mysql_insert_id - ideas? Suggestions?
As requested table structures:
CREATE TABLE IF NOT EXISTS `blogs` (
`id` int(11) NOT NULL auto_increment,
`url` text NOT NULL,
`user` text NOT NULL,
`pass` text NOT NULL,
`dname` text NOT NULL,
`islocal` varchar(3) NOT NULL,
`cat2post` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
CREATE TABLE IF NOT EXISTS `blogstags` (
`id` int(11) NOT NULL auto_increment,
`tag_id` int(11) NOT NULL,
`blogstags_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `tags` (
`id` int(11) NOT NULL auto_increment,
`tag` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
mysql_insert_id() is working fine. The problem could be that you are using persistant connections. With persistant connections, all kinds of funky concurrency issues can happen. Don't use them unless you really, really have to.
Two options - you could switch to PostgreSQL which allows you to return an auto_incremented ID as part of the insert query.
Or, if you are sticking with MySQL, you can use the MySQL LAST_INSERT_ID() function -