我有一个 mysql 查询:
$analyse_ot1="SELECT COUNT(*) AS ot_count FROM first, base, users
WHERE base.base_id=$base
AND
users.base_id=$base
AND
users.id=first.user_id
AND
first.$sub='OT'";
$result_ot1=mysqli_query($con,$analyse_ot1);
$row_ot1= mysqli_fetch_assoc($result_ot1);
$total_ot1= $row_ot1['ot_count'];
$otper1=($total_ot1/$total)*100;
我将在网页上多次重复使用此代码,并希望能够将其作为循环的一部分运行。
我不想每次都重命名我的变量(其中 $result_ot1 变成 $result_ot2 等...)
我尝试引入索引变量 $x,然后将其附加到另一个变量名称:
$x=2;
$result_ot.$x=....
但是,它不想工作。
有什么建议吗?我有一个想法,可能需要数组,但我担心查询会抛出数组,并且我不确定数组中的数组不会让我的计算机着火......
最佳答案
在任何地方使用查询的提示。
//declare this in a folder, 'functions.php', for example
function analyse($base, $sub, $con)
{
$analyse_ot1 = 'SELECT COUNT(*) AS ot_count FROM first, base, users'
." WHERE base.base_id=$base AND users.base_id=$base"
." AND users.id=first.user_id AND first.$sub='OT'";
$result_ot1 = mysqli_query($con, $analyse_ot1);
$row_ot1 = mysqli_fetch_assoc($result_ot1);
return $row_ot1['ot_count'];
}
在项目的任何其他地方:
include 'functions.php';
$total_ot1 = analyse($base, $sub, $con);
$otper1 = ($total_ot1 / $total) * 100;
我不太了解循环的事情。但是为了将结果保存在数组中,您可以这样做:
$totalCounts = [];
foreach(loop){
$total_current = analyse($base, $sub, $con);
$totalCounts[] = $total_current;
}
您将拥有 $totalCounts
,它将是我们在函数中找到的查询结果的数组。这可能是一种将结果保存在数组中的方法。
您也可以将其关联起来:
$x = 0;
foreach(loop){
$total_current = analyse($base, $sub, $con);
$totalCounts['count_'.$x] = $total_current;
$x++;
}
因此,例如,如果您现在访问:$totalCounts['count_3']
,您将访问第三个循环的查询结果。
我不知道这是否是你的答案。但也许这有点帮助。
关于php - 通过连接 2 个变量创建索引变量 - php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38370349/