Skip to content
Advertisement

chose another column if the first column is null

how to chose another column if the first one is null i have users table who have

email phone and other data i have registration form built with php what i want is check if user insert an email or phone if he insert an email and phone check if the email is in MySQL DB if he doesn’t insert email in the form and just insert phone number i want to check if the phone number is in the MySQL DB

what i’m trying to say is like this flowchart :

select email, phone where email =$email 
if email is null 
    select phone where phone =$phone 
else 
   select email where email = $email

NOTE the phone number is required in the form so it cant be the both email and phone null

i tried if statements COALESCE() but i always not getting what i expected which is the num_rows

$chk_query = " SELECT email,phone FROM users WHERE email = '$email' IF (email IS NULL)
                SELECT phone WHERE phone = '$phone' ";
                $result = $mysqli->query($chk_query);
                if ($result->num_rows > 0 ){
                    $_SESSION['message'] = 'The Email or Phone number you enter it is exist ! ';
                }
                else{
                    // insert data to the database after checking

Advertisement

Answer

I have two options depending on one question – if email and phone are not null and phone exists in the database, do you want to raise the error or enter the new data?

If you always want to check if the email or phone exists then could you just use OR?

$chk_query = " SELECT coalesce(email,phone) FROM users WHERE email = '$email' OR phone = '$phone' ";
            $result = $mysqli->query($chk_query);
            if ($result->num_rows > 0 ){
                $_SESSION['message'] = 'The Email or Phone number already exists';
            }
            else{
                // insert data to the database after checking

If you want to ignore the phone when email has been entered then add an extra condition (whilst only returning the first non-null column

$chk_query = " SELECT coalesce(email,phone) FROM users WHERE email = '$email' OR (email IS NULL AND phone = '$phone') ";
            $result = $mysqli->query($chk_query);
            if ($result->num_rows > 0 ){
                $_SESSION['message'] = 'The Email or Phone number already exists';
            }
            else{
                // insert data to the database after checking

The coalesce will choose the first non-null value in the list of columns. Note this will only work if values are truly null, not if they are empty strings.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement