skip to Main Content

I have created a basic website that has a form. This form captures the following information from a user and stores it in the PHPMyAdmin table:

First Name, Surname, Title, Description, Email Address, Display Email Address (Yes/No).

An example of input would be:

David, Beckham, Mr, Hello I am a boy, [email protected], Yes

Also on the website, I have a table that shows a list of all the users stored in my database through the use of this PHP code:

$sql = "SELECT UserID, UserForeName, UserSurname, UserTitle, UserDescription, 
UserEmailAddress FROM Users";

How would I edit this SQL so that if a user answers “No” to the “Display Email” field, their row would omit their email address from the row. For example:

David, Beckham, Mr, Hello I am a boy, [email protected], Yes

Lucy, Sky, Mrs, Hello I am a girl, , No

I have tried the following query, but have had no luck so far:

SELECT CASE WHEN EmailReveal = 'yes'
        THEN SELECT *
        ELSE SELECT UserID, UserForeName, UserSurname, UserTitle, UserDescription
   END AS col 
FROM Users;

3

Answers


  1. you can use union but for that you have to be same number of column so you could use ” blank string for making same number of column in both selection

     SELECT UserID, UserForeName, UserSurname, UserTitle, UserDescription 
    ,col1,col2 ---coln FROM Users
     where EmailReveal = 'yes'
     union
      SELECT UserID, UserForeName, UserSurname, UserTitle, UserDescription ,
     '',''--''
     FROM Users
     where EmailReveal <> 'yes'
    
    Login or Signup to reply.
  2. SELECT 
        UserID, 
        UserForeName, 
        UserSurname, 
        UserTitle, 
        UserDescription, 
        CASE WHEN showemailcondition THEN UserEmailAddress ELSE '' END `Email`
    FROM Users
    

    This is how you would use a CASE WHEN in a simple way for this.

    Login or Signup to reply.
  3. Please try this query:

    $sql = "SELECT UserID, UserForeName, UserSurname, UserTitle, IF(UserEmailAddress = 'Yes',UserDescription,'') AS UserDescription,UserEmailAddress FROM Users";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search