Search code examples
phpmysqlcloud9

PHP & MySQL - If content is not in one table, check another


I am trying to set an if/else case to see if a value is in one table and then display said value, and if it's not in one table, to check the other table.

I am working with PHP and MySQL in Cloud 9. The email is obtained from a form which is not shown.

Searching the table "Customer" with the correct email displays the password_enc, but if the email is not found in the Customer table, and it searches the "Company" table, is doesn't display anything. I checked PHPMyAdmin and the email is present and valid

I've also checked my tables, and "email" and "rep_email" are valid.

Is there an easier way to do this, or does my current code need tweaking? Thank you for your help.

$email              = !empty($_POST ['email']) ? $_POST['email'] : "";
$email2             = $email;


$query  = "SELECT * FROM Customer WHERE email = '$email'";
$result = $db->query($query);

if ($result){
    $row            = $result->fetch_assoc(); /* These lines query the dataabse when user enters email */
    $password_enc   = $row['password_enc'];
}
elseif(!$result){
    $query2         = "SELECT * FROM Company WHERE rep_email = '$email2'";
    $result2        = $db->query($query2);
    $row2           = $result2->fetch_assoc(); /* These lines query the dataabse when user enters email */
    $password_enc   = $row2['password_enc'];
}

echo "password_enc: ".$password_enc;

Solution

  • For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object

    Php mysqli Manual

    So instead of checking the response you can actually check number of rows returned like this

    $query  = "SELECT * FROM Customer WHERE email = '$email'";
    $result = $db->query($query);
    
    if ($result->num_rows > 0){
       $row            = $result->fetch_assoc(); /* These lines query the dataabse when user enters email */
       $password_enc   = $row['password_enc'];
    }else{
       $query2         = "SELECT * FROM Company WHERE rep_email = '$email2'";
       $result2        = $db->query($query2);
       if($result2->num_rows>0){
          $row2           = $result2->fetch_assoc(); /* These lines query the dataabse when user enters email */
          $password_enc   = $row2['password_enc'];
       }
    }
    
    if(isset($password_enc)){
       echo "password_enc: ".$password_enc;
    }else{
       echo "Password Not Available";
    }