I am fetching some results using
$result=mysql_query("SELECT * FROM mobiles");
this mobiles
table has got 9 columns as
id,name,imei1,imei2,imei3,imei4,imei5,qty,price
some of the imei fields will be/are empty which i do not want to select in the query, as in every row the NULL, NOT NULL is varying.
I needed to ask if there is any query which will select only columns which are not null/empty.
The normal way, mysql_num_fields()
return a value 9, it should return value 7 if imei4 and imei5 were empty.. etc etc
I can also hardcode it as WHERE imei1 IS NOT NULL
but i wanted it to be generated rather than hardcoded.
The reason i am looking for this sort of query is,
<select class="form-sell" name="imei">
<?php if(!empty($row['imei1'])){?><option value="<?php echo $row['imei1']; ?>"><?php echo $row['imei1']; ?></option><?php } ?>
<?php if(!empty($row['imei2'])){?><option value="<?php echo $row['imei2']; ?>"><?php echo $row['imei2']; ?></option><?php } ?>
<?php if(!empty($row['imei3'])){?><option value="<?php echo $row['imei3']; ?>"><?php echo $row['imei3']; ?></option><?php } ?>
<?php if(!empty($row['imei4'])){?><option value="<?php echo $row['imei4']; ?>"><?php echo $row['imei4']; ?></option><?php } ?>
<?php if(!empty($row['imei5'])){?><option value="<?php echo $row['imei5']; ?>"><?php echo $row['imei5']; ?></option><?php } ?>
</select>
i understand that this is not a convenient way to get the values as hardcoded, but i will get them in a loop once i am able to get the mysql_num_fields value and subtracting 4 from that value, for example
$value = mysql_num_fields($result)
$numColums = $value-4;
// Now as from my table, 3 is left from row1 and 2 is left from row2, I can use a for loop to get the select options.
Answer
<?php
$result=mysql_query("SELECT * FROM mobiles");
$columnCount = mysql_num_fields($result)-4; // subtracted static column numbers (id,name,qty,price)
?>
<select class="form-sell" name="imei">
<?php
// while numebr of imei fields run
for($i=1;$i<=$columnCount;$i++){
$imei = "imei" . $i;
if(!empty($row[$imei])){
?>
<option value="<?php echo $row[$imei]; ?>"><?php echo $row[$imei]; ?></option>
<?php
}//if
}//for
//if at some point user adds more imei colums as 6 7 8 9 and so on, 4 colums will
//always be subtracted giving remaining imei colums only and displaying them in loop
?>
</select>