我有一个音乐数据库,我试图检查用户是否输入了重复的专辑。当专辑标题和艺术家名称都相同时,它会给出错误并且不会按预期插入数据。它也适用于当它是不同的艺术家,但相同的专辑名称。但是当它是数据库中已有艺术家的新专辑时,PHP将执行if和else块。
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";