I have a music database and I'm trying to check whether the user entered a duplicate album. When both the album title and artist name are the same, it gives an error and does not insert the data as expected. It also works for when it's a different artist but the same album name. But when it's a new album by an artist already in the database, PHP executes both the if and else blocks.
function getDB(){
try{
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', '', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}catch(Exception $e){
echo $e->getMessage();
}
}
function duplicateAlbum(){
$db = getDB();
$stmt = $db->prepare("select * from artist join album on artist.id = album.artist_id where name = ? and title = ?");
$stmt->execute(array($_POST['artist'],$_POST['title']));
echo $stmt->rowCount() != 0;
return $stmt->rowCount() != 0;
}
function echoResults(){
$db = getDB();
$albums = $db->prepare("select * from album where title = ?");
$albums->execute(array($_POST['title']));
$artists = $db->prepare("select * from artist where name = ?");
$artists->execute(array($_POST['artist']));
$results = array("albums" => $albums->fetchAll(PDO::FETCH_ASSOC), "artists" => $artists->fetchAll(PDO::FETCH_ASSOC));
echo json_encode($results);
}
function addAlbum($artist, $title, $genre, $released){
$db = getDB();
$stmt = $db->prepare("select id from artist where name = ?");
$stmt->execute(array($artist));
$artistresult = $stmt->fetchAll(PDO::FETCH_ASSOC)[0]['id'];
$stmt = $db->prepare("insert into album values (?,?,?,?)");
$stmt->execute(array($title, $genre, $released,$artistresult));
}
if(!duplicateAlbum()){
addAlbum($_POST['artist'],$_POST['title'],$_POST['genre'],$_POST['released']);
echoResults();
}
else echo "Duplicate album";
duplicateAlbum()gets called? Looks like it does twice.