0

I have a SQL routine written that compares a user's input with an existing value in a table. If the value exists, a green check mark appears next to the input. If it doesn't, then a red x appears. My SQL statement is as follows:

      $check = $con->prepare("SELECT count(*) FROM emaillist");
      $check->execute();
      $result = $check->fetchColumn(); //Get no. of columns
      $check = $con->prepare("SELECT Username FROM emaillist WHERE Username =                                                                                                                                                                                                                               
              '$Name' AND '$Name' <> '' ");
      $check->execute();
      $result = $check->fetchColumn(); //Get exact column
      if(!$result) {
               show red x } else { show green check }

This works fine as long as there is input. The red x appears when the input doesn't match and the green check appears when it does; however, I don't want anything to display if the field is left blank. Right now, the red x appears if the field is empty or is null. Using IS NOT NULL didn't work, either. What am I missing?

1
  • If $Name is coming from a user input then I think it would be better to check for its validity independent of the SQL query rather than putting it in the query itself. Commented Oct 2, 2013 at 20:57

2 Answers 2

2

You only have two branches: show red x and show green check. You need a third, e.g.

if (!$Name) {
    //show nothing
}
else if (!$result) {
    //show red x
}
else {
    //show green check
}

On an unrelated note, it's great that you're using PDO but you need to properly parameterize your queries to be safe from injection.

Sign up to request clarification or add additional context in comments.

1 Comment

No worries. When this goes into production, we'll be using named placeholders. This is just a prototyping exercise. ;-)
1

Try rewriting your logic like this:

if ($Name != ''){
    $check = $con->prepare("SELECT Username FROM emaillist WHERE Username = '$Name'");
    $check->execute();
    $result = $check->fetchColumn(); //Get exact column
    if(!$result) {
          // show red x 
    } else { 
         // show green check 
    }
}
else {
    // show red here or some other input error message
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.