我需要为多个行计算一个MySQL数据库行的列中存在的元素的数量,并将它们加在一起。这是我用来计算数组元素数量(用逗号分隔的数字)的代码:
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
但是现在我需要为每一行执行此操作,这可能会因查询而异。我需要将每一行的$result
加在一起以获得所有行的最终总和。我使用了以下代码,但输入的值不正确,有人可以指出正确的方向吗?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
答案 0 :(得分:1)
用以下代码替换代码:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;
答案 1 :(得分:1)
您只是获取1行,然后尝试对该行进行计数,而您需要遍历这些行并在其中添加字段...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;