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
Related
I am using MySQL and I think it has something to do with Id's. I want every new image I upload to show up first in a order. Here is my code:
This allows the images to display:
<?php
$db = mysqli_connect("localhost", "root", "", "photos");
$sql = "SELECT * FROM images";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<a href='uploads/".$row['image']."'> ";
echo "<img id='img_div' src='uploads/".$row['image']."'/>";
echo "</a>";
}
?>
Here is my image structure:
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`image` varchar(200) NOT NULL,
`text` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `images` (`id`, `image`, `text`) VALUES .....
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
ALTER TABLE `images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=129;
$sql = "SELECT * FROM images ORDER BY id DESC";
Should do the trick!
I have this task from school, and I am confuse and lost on how I got to do this.
So basically I have to create 2 tables to the database but I have to created from php.
I have created the first table, but not the second one for some reason.
And then, I have to populate first and second tables with 10 and 20 sample records respectively, populate, does it mean like adding more fake users? if so is it like the code shown below?
*I got error on the populating second part as well
Thank you so much for the help.
<?php
$host = "host";
$user = "me";
$pswd = "password";
$dbnm = "db";
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("<p>Database Not Selected</p>");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL,
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
The others have addressed one of your issues, so this is in relation to not being able to add values to your tables (populate). Your connection link is $conn -
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
ie.
$query_result1 = #mysqli_query($conn, $sql);
but when you are adding your values to the tables, you changed your connection link to $dbConnect
...
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
...
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
To insert multiple values into your table you could add a comma and additional parentheses ,() -
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2),(2,3),(3,1)";
$queryResult13=#mysqli_query($conn,$sqlSt13);
Or you could use mysqli_multi_query, and list each one-
//populating 2nd table
$sqlSt13 ="INSERT INTO myfriends VALUES (1,2);";
$sqlSt13 .="INSERT INTO myfriends VALUES (2,3);";
$sqlSt13 .="INSERT INTO myfriends VALUES (3,1);";
$queryResult13=#mysqli_query($conn,$sqlSt13);
see the manual for mysqli_multi_query - php.net/manual/en/mysqli.multi-query.php
You have an extra comma here that might cause an error:
friend_id2 INT NOT NULL,
should be:
$sqlMyfriends = "CREATE TABLE `myfriends` (
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
I wish I could be at school now :)
You have the following errors in code:
1) $queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
Is correct: $queryResult3 = #mysqli_query($dbConnect,$sqlSt3);
2) $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL,
)";
Is correct: $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL)";
3) $queryResult3 = #mysqli_query($conn,$sqlSt3);
Is correct: $queryResult3 = mysqli_query($conn,$sqlSt3);
Code correct is:
Couldn't connect to the server!");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("Database Not Selected");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = mysqli_query($conn,$sqlSt3);
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
I hope to help !
Is it true that after a user signs up, a sql table is create for him to store his posts ?
I make it similar in mysql after the man insert him into my page. The database is the same name with but the table name is made when he log in first time.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
public function Users($username)
{
$table_name=$username."_tb";
echo $table_name."<br/>";
mysql_connect(localhost,$username, $password) or die("unable to connect to database ".mysql_error());
echo $database."<br/>";
mysql_selectdb($database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL)";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
But it display only table_name and an error, the database name not display. Error is NO DATABASE IS SELECTED/
EDIT
This class is call after he sign up
I also have a function postApost but when I do
ob_start();
session_start();
require("Users_DB.php");
$name=$_SESSION['user'];
echo 'Welcome '.$name;
$username=new UserDB($name);
there is no table created
Two variables with same name $username. Use $this for accessing variable of class. Missing quote(") with localhost - it must be string type parameter. and this code can't create table on Database because you use AUTO_INCREMENT on your code but forgot to mention that as a PRIMARY KEY. I think the following code help you a lot.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
function __construct($user_name)
{
$this->table_name=$user_name."_tb";
echo $this->table_name."<br/>";
mysql_connect("localhost",$this->username, $this->password) or die("unable to connect to database ".mysql_error());
echo $this->database."<br/>";
mysql_selectdb($this->database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$this->table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL, PRIMARY KEY (id))";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
And you can use this class by the following way :
$clsName = new Users('username');
Create one table:
CREATE TABLE Posts (
id TINYINT(4) NOT NULL AUTO_INCREMENT,
user VARCHAR(20) NOT NULL,
title VARCHAR(128) NOT NULL,
date_post DATETIME,
date_edit DATETIME,
post_content TEXT NOT NULL
)
Inserting new posts:
$insert = "
INSERT INTO Posts (
user,
title,
date_post,
date_edit,
post_content
) VALUES (
'$username',
'$title',
NOW(),
NOW(),
'$post_content'
)
";
Updating is simple:
$update = "
UPDATE Posts SET
title = '$title',
post_content = '$post_content',
date_edit = NOW()
WHERE id = '$postid';
";
Get all posts for user:
$posts = "
SELECT title, date_post, date_edit, post_content
FROM Posts
WHERE user = '$username'
ORDER BY date_post
";
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.
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 -