我有两个查询计算数据库中“艺术家”和“组”的数据数量。我想显示一条消息,如果有艺术家或团体(或两者)都有数据显示,如果两个数据都返回0,那么就不显示任何内容。
我有以下代码似乎不起作用:
<?php if (($numrowsartists==0)OR($numrowsgroups==0)) {
} else {
echo "There is information to display.";
}
?>
以下是我的查询:
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$numrowsartists = mysql_fetch_assoc($res);
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$numrowsgroups = mysql_fetch_assoc($res);
提前致谢。我敢肯定它可能是一个超级基本的修复,但我仍然是非常新的PHP,并希望得到一些帮助。
答案 0 :(得分:1)
你应该得到行的值,例如使用列名
的别名$query = "SELECT COUNT(*) as num_artists FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsartists = row['num_artists'];
$query = "SELECT COUNT(*) as num_groups FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsgroups = row['num_groups'];
答案 1 :(得分:0)
有几种解决方案,最简单的方法如下:
if($numrowsartists[0]+$numrowsgroups[0] > 0)
然而,正如人们所说,你不应该再使用mysql_ *函数了。 假设ID是用户输入,您应该使用预准备语句。 此外,您可以在单个查询中处理这两个测试:
$stmt = $con->mysqli_prepare("SELECT COUNT(1) as `count` FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = ?");
$stmt->bind_param('i',$id);
$stmt->execute();
if($stmt->get_result()->fetch_array()[0] > 0){
...
}else{
//message that nothing was found
}