I'm developing an application in which I need to click if any of the fields in a row is empty or not. If any of the fields is empty, then the variable $flag
should be 1, other wise zero. I have written till here, but I'm not sure what to do next to check if each and every field is null/empty or not.
public function profileComplete($email)
{
global $conn;
$flag=0;
try
{
$s = $conn->prepare("SELECT * from users where emailid = : email");
$s->bindParam(":email",$email);
$s->execute();
$s->setFetchMode(PDO::FETCH_OBJ);
while($row = $s->fetch())
{
}
}
}
How should I code to make it work according to the requirements? All suggestions are appreciated.
Id go with array filter and count the row, to avoid the inner loop.
$num_fields = 8; //should know this before hand but you could compare $row and $_row below but it would be more expensive to run.
while($row = $s->fetch()){
$_row = array_filter($row); //removes all empty elements
if(count($_row) != $num_fields){
//some fields are empty
}
}
if you consider 0 empty this will be fine. - note - that empty() will also treat 0 as empty, if you need the 0 as not empty you can use a custom function in array_filter for the callback with the === 0 strict equality or !== 0 to check for that.
empty() treats these values as empty - and will return TRUE on them.
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
public function profileComplete($email)
{
global $conn;
$flag=0;
try
{
$s = $conn->prepare("SELECT * from users where emailid = : email");
$s->bindParam(":email",$email);
$s->execute();
$s->setFetchMode(PDO::FETCH_OBJ);
while($row = $s->fetch())
{
foreach($row as $r){
if(is_null($r) || $r==''){
$flag=1;
}
}
}
}
}
while($row = $s->fetch())
{
foreach($row as $val)
{
if(empty($val)) { $flag = 1; }
}
}
'empty()' assumes you want to catch null, false, empty strings, and zeros. If you don't want to catch zeros/false, use if(is_null($val) || $val == '') { $flag = 1; }
Try this although I haven't checked the output. Hope it helps you! :)
while($row = $s->fetch()){
foreach($row as $rowval){
if($rowval == null || empty($rowval)){
$flag=1;
}
}
}