ika ika - 6 months ago 16
PHP Question

How can I keep from inserting duplicate rows in MySQL?

I have been trying to save RSS articles in my database (from RSS URL) and it is working. But now I want to prevent inserting duplicate articles (rows) and I have tried the coding below but it doesn't work. Every time it runs, it all seems to work fine except it inserts all the articles and doesn't stop the duplication (article exists New Record has id 144). Why is this happening?

$doc = new DOMDocument();
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
$itemRSS = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'description' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,

array_push($arrFeeds, $itemRSS);

$mysqli = new mysqli('localhost', '', '', 'testdb');

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());

$check=mysqli_query($mysqli,"select * from `articles` where `title`=`title` and `description`=`description`");
$checkrows=mysqli_num_rows($check);if (!$check) { die('Invalid query: ' . mysql_error());}

if($checkrows>0) {
echo "article exists";

if ($stmt = $mysqli->prepare("INSERT INTO `articles` (`title`, `description`, `link`) VALUES (?, ?, ?)")) {
$stmt->bind_param('sss', $title, $description, $link);}

else {die("Errormessage: ". $mysqli->error);}

foreach( $arrFeeds as $RssItem){
$title = $RssItem["title"];
$description = $RssItem["description"];
$link = $RssItem["link"];


printf ("New Record has id %d.\n", $mysqli->insert_id);



Your insert query is in if($checkrows>0) condition's true branch. Move it to the false branch, under else.