我将不胜感激,如果有人可以帮助我解决我的问题,将数据从XML文件插入数据库中。我想在刷新页面后防止在数据库中添加重复行。这是我的代码:
public function getAll() {
$xml = new DOMDocument();
$xml->load('newXMLDocument.xml');
$xmldata = $xml->getElementsByTagName('book');
$xmlcount = $xmldata->length;
for($i=0; $i< $xmlcount; $i++){
$author = $xmldata->item($i)->getElementsByTagName('author')->item(0)->childNodes->item(0)->nodeValue;
$name = $xmldata->item($i)->getElementsByTagName('name')->item(0)->childNodes->item(0)->nodeValue;
try {
$statement = self::$db->prepare("INSERT INTO `books`( `Author`, `Name`) values( ?, ?) ");
$statement->bindParam(1, $id);
$statement->bindParam(2, $author);
$statement->bindParam(3, $name);
$statement->execute(array(
$author,
$name
));
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
在您的循环内,然后在插入数据之前,在提交之前检查值是否存在,然后运行if语句以防止运行查询,以防止插入查询。
for loop
$query = 'SELECT `Author`,`Name` from `table` where `Author` = $author AND `Name` = $name';
if($query != null){
insert new row
}
end for loop