Reputation: 5
I use this code below for getting data from a different website by using PHP curl function.everything is working fine but I am getting duplicate data into my database when the website will reload or refresh.
duplicate data screenshot
does there have any why based on this code below to stop inserting duplicate data on reload if the data already exist in the Mysql database? I search on google about this issue but don't get any useful information.
if(isset($_POST['url'],$_POST['theme'])){
$db = new Mysqli("localhost" , "iamniloy_wp###" , "(5uSE6[3OP" , "iamniloy_#@");
$url = $db->real_escape_string($_POST['url']);
$theme = $db->real_escape_string($_POST['theme']);
$query = "INSERT INTO twist_data ( url,theme ) VALUES ('$url','$theme')";
$db->query($query);
}
Upvotes: 0
Views: 2394
Reputation: 522626
If you can't add a unique index for whatever reason, you can use EXISTS
to check for an already existing record:
INSERT INTO twist_data (url, theme)
SELECT * FROM (SELECT '$url','$theme') AS tmp
WHERE NOT EXISTS (
SELECT * FROM twist_data WHERE url = '$url' AND theme = '$theme'
)
Upvotes: 1
Reputation: 156
Replace the last two ligne with this code:
$query = "select * from twist_data where url='$url'";
$db->query($query);
if($db->num_rows>0){
$query = "INSERT INTO twist_data ( url,theme ) VALUES ('$url','$theme')";
$db->query($query);
}
Upvotes: 0
Reputation: 311
Use the ON DUPLICATE
key words in your insert query. See: INSERT ... ON DUPLICATE KEY (do nothing)
And set the column's index to unique.
Upvotes: 0
Reputation: 70
Create a Select count query where in you will check if the data exists or not then make an if condition. if it is true, then don't insert, if it has no data (false), insert a query.
Ex:
Select count(*) from twist_data where url='".$url."';
Upvotes: 0
Reputation: 62666
You should change the structure of your table to have a unique index on the relevant columns.
For example:
ALTER TABLE `twist_data` ADD UNIQUE INDEX `url` (`url`)
This way you will not able to insert the same url
to your table.
If you need the unique
to be on both the url
and the theme
you can use:
ALTER TABLE `twist_data` ADD UNIQUE INDEX `url_theme` (`url`, `theme`)
More information in the MySQL Documentation.
Upvotes: 0