我有一个音乐数据库,我正在尝试检查用户是否输入了重复的专辑。当专辑标题和艺术家姓名相同时,它会给出一个错误,并且不会按预期插入数据。它也适用于不同的艺术家,但相同的专辑名称。但是当它是已经在数据库中的艺术家的新专辑时,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";发布于 2017-07-21 07:57:25
不可能在同一次运行中同时命中两个( if /else),如果这两种情况都发生了,是因为您正在运行脚本两次,或者有东西再次调用它。我建议你分析你的代码执行流程
发布于 2021-03-24 14:32:42
当if块中有一些异常时,有时会发生这种情况。我也面临着同样的问题。这是因为我在if块中的方法调用中出现了一些错误。在调试时,我可以看到控件在两个块中都在运行。
duplicateAlbum()或echoResults()可能有一些问题。
https://stackoverflow.com/questions/45226890
复制相似问题