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?
You only have two branches: show red x and show green check. You need a third, eg
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.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.