简体   繁体   中英

Using php if…else statement with two queries

I have two queries that count the number of data for both "artists" and "groups" in my database. I want to display a message if there is data to display for either artists or groups (or both), and if the data returns 0 for both of them then not to display anything.

I have the following code which doesn't seem to work:

<?php if (($numrowsartists==0)OR($numrowsgroups==0)) {

 } else {
        echo "There is information to display.";
        }
?>

Below are the queries I have:

$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);

Thanks in advance. I'm sure it's probably a super basic fix but I'm still very new to php and would appreciate some help.

You should getthe value frorm the row eg using alias for column name

$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'];

There are several solutions, the easiest being the following:

if($numrowsartists[0]+$numrowsgroups[0] > 0)

However, as people have said, you shouldn't use mysql_* functions anymore. Assuming the ID is user input, you should really use prepared statements. Also, you can handle both tests in a single query:

$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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM