Pregunta

I have made the following script to check if an article exists in another table, if it does it is supposed to echo that the article exists, if it doesnt it then adds the article id and article name to another table. The problem I am having is if I clear the workshoptabs table and run the update script it creates all the article id / names, but if I add a new article to the dbel6_content table and then run the update script again, it doesn't add the new articles to the workshoptabs. Also if I delete a record from workshoptabs and run the script it doesnt re add it, but if I clear the whole table it re imports everything then.

$resultB = mysql_query("SELECT * FROM dbel6_content WHERE catid='12'") or die(mysql_error());  
while($rowB = mysql_fetch_array( $resultB )) {
  $articleid = $rowB['id'];
  $articlename = $rowB['title'];

  $resultA = mysql_query("SELECT * FROM workshoptabs WHERE articleid='$articleid'") or die(mysql_error());  
  while($rowA = mysql_fetch_array( $resultA )) {
    $articleexists = $rowA['articleid'];
    echo $articleexists.' Exists';
  }

  if (empty($articleexists)){
    mysql_query("INSERT INTO workshoptabs (articleid, articlename) VALUES ('$articleid', '$articlename')") or die(mysql_error()); 
    echo 'Added Articles : '.$articleid.'-';    
  }
}

If I run the script I get : 16 Exists17 Exists20 Exists24 Exists25 Exists26 Exists27 Exists34 Exists

If I wipe the workshoptabs table and reimport everything I get : Added Articles : 16-Added Articles : 17-Added Articles : 18-Added Articles : 19-Added Articles : 20-Added Articles : 21-Added Articles : 22-Added Articles : 23-Added Articles : 24-Added Articles : 25-Added Articles : 26-Added Articles : 27-Added Articles : 34-

But if for example I now delete article 21 and run the script again it doesnt add it.

¿Fue útil?

Solución

I suggest using the row count of your query to determine if a record exists:

<?php

  $resultB = mysql_query("SELECT * FROM dbel6_content WHERE catid='12'") or die(mysql_error());

  while($rowB = mysql_fetch_array( $resultB )) {

    $articleid = $rowB['id'];
    $articlename = $rowB['title'];

    $resultA = mysql_query("SELECT * FROM workshoptabs WHERE articleid='$articleid'") or die(mysql_error());

    if (mysql_num_rows($resultA)>0) {
      // exists
      echo $articleid.' Exists';
    } else {
      // doesnt exist
      mysql_query("INSERT INTO workshoptabs (articleid, articlename) VALUES ('$articleid', '$articlename')") or die(mysql_error()); 
      echo 'Added Articles : '.$articleid.'-';  
    }

  }

?>

Consider looking into PDO or MySQLi, as mentioned by Joseph.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top