我需要编写一个方法,允许我计算用户填充的行数。 例如:
User Name Age Country Gender Height
1 Mike 34 USA Male 6
2 Bill 23 CA 5
3 Jane 31 USA
在上面的例子中,我想查询数据库并返回一个反映用户记录完成程度的值。如:
User 1 = 100% complete
User 2 = 80% complete
User 3 = 60% complete
我正在使用Codeigniter 3.你能帮助我吗?
答案 0 :(得分:3)
您可以尝试这样::
$result = mysql_query('SELECT * FROM `MyTable`');
while($row = mysql_fetch_row($result)){
$empty_count = 0;
$count = count($row);
for($i = 0; $i < $count; $i++)
if($row[$i] === '' || $row[$i] === 'NULL')
$empty_count++;
echo 'User '.$row[0].' = '.((int)(100*(1-$empty_count/($count-1)))).'% complete';
}
希望它能奏效。
答案 1 :(得分:2)
使方法传递方法
中的参数 function profileCompleted($user){
$percentage = 0;
$sql ="SELECT * FROM user WHERE user=$user"
$query = $this->db->query($sql);
if ($query->num_rows() > 0)
{
$notEmpty = 0;
$totalField =5;
foreach ($query->result() as $row)
{
$notEmpty += ($row->Name != '') ? 1 : 0;
//do with all field
}
$percentage = $notEmpty/$totalField *100;
}
return $percentage.'%';
}
答案 2 :(得分:2)
我认为它也可以通过SQL查询来完成:
SELECT id,
(
CASE name WHEN NULL THEN 0 ELSE 1 END
+
CASE WHEN age IS NULL THEN 0 ELSE 1 END
+
CASE country WHEN '' THEN 0 ELSE 1 END
+
CASE gender WHEN '' THEN 0 ELSE 1 END
+
CASE WHEN height IS NULL THEN 0 ELSE 1 END
) * 100 / number_of_fields AS complete
from your_table;