Skip to content
Advertisement

How can you assign a value to a variable if mysql does not yield any result?

There are two databases. I am trying to see if email in the first database is also present in the second database. Here’s the code that I’ve tried:

// Getting info from the first "subscribers" database.
 
$sql = "SELECT name, email, status 
        FROM subscribers 
        WHERE status='active'";

$result = mysqli_query($link,$sql);

while($row = mysqli_fetch_assoc($result)) {

    // To check if all emails in "subscribers" database are also present in "phpbb_users" database. 
    // If they are present then user type=0 otherwise user type=1.

    $subscriber_email = $row['email'];
    $forum_sql = mysqli_query($forum_link, "SELECT user_type 
                                            FROM phpbb_users 
                                            WHERE user_email='$subscriber_email'");

    while($forum_row = mysqli_fetch_assoc($forum_sql)){
        $ut = $forum_row['user_type'];
        if($ut=="0"){
            $type="0";
        } else {
            $type="1";
        }
        echo $type;
    }   

    // To diplay the data from "subscribers" database.
    echo $row["name"]; 
    echo $row['email'];
} 

The output is:

enter image description here

The type for onera and julian is blank because there email is not present in the phpbb_users database. How can I avoid this blank space and make it 1 or anything else. var_dump() shows nothing.

Advertisement

Answer

This is a simple logical issue in the code with this section:

while($forum_row = mysqli_fetch_assoc($forum_sql)){
    $ut = $forum_row['user_type'];
    if($ut=="0"){
        $type="0";
    } else {
        $type="1";
    }
    echo $type;
}

If the user is not in the second table, then this code will never run. So type is never output.

Reorganise the code so that type is set by default and always output, even if there is no row in the second table:

$type = "1";
while($forum_row = mysqli_fetch_assoc($forum_sql)) {
    $ut = $forum_row['user_type'];
    if($ut == "0"){
        $type = "0";
    }
}
echo $type;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement