Tutaj dokładnie przedstawię kod jaki udało mi się stworzyć a który chciałbym zoptymalizować.
Baza danych to MySQL.
Struktura:
Tabela articles: (id, title, itp.)
Tabela tags: (id,name).
Tabela tags_ref (id, artId, tagId).
I działający kod.
public function updateTags($artID,$tags){
foreach ($tags as $tag) {
try {
$checkTag = $this->db->query("SELECT id FROM tags WHERE name = '$tag' ");
if($checkTag ->rowCount()!=1){
$inserTag = $this->db->prepare("INSERT INTO tags (id,name) VALUES (NULL,:tag)");
$inserTag->bindValue(':tag', $tag, PDO::PARAM_STR);
$inserTag->execute();
$this->addTagsRef($artID,$this->db->lastInsertId());
}else{
$tagID = $checkTag->fetch();
$this->addTagsRef($artID,$tagID[0]);
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
private function addTagsRef($artID,$tagId){
try {
$inserTagRef = $this->db->prepare("INSERT INTO tags_ref (id,artId,tagId) VALUES (NULL,:artID,:tagRef)");
$inserTagRef->bindValue(':artID', $artID, PDO::PARAM_INT);
$inserTagRef->bindValue(':tagId', $tagId, PDO::PARAM_INT);
$inserTagRef->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
}
I teraz to fundamentalne pytanie, jak to można poprawić?
Dziękuję