我有一个连接到数据库的查询,它按设计工作,但我觉得我需要更多的代码。有人可以帮助我吗?
基本上我试图获得多个列的总和,然后为结果分配一个变量。变量必须每次都是唯一的,所以我可以在以后单独回显它们。
是否可以使用数组选择不同的列,然后使用相同的数组来生成变量?
我希望这一切都是我想要实现的目标。
这个例子只是我拥有的12个查询中的3个。
$sql = ("SELECT SUM(Case_closed) AS sum_closed FROM production WHERE Datum = '$actual_time' AND jaar = '$year' ");
$result = mysqli_query($connect, $sql) ;
$Case_closed = $result->fetch_object()->sum_closed;
$sql = ("SELECT SUM(Case_handled) AS sum_handled FROM production WHERE Datum = '$actual_time' AND jaar = '$year' ");
$result = mysqli_query($connect, $sql) ;
$Case_handled = $result->fetch_object()->sum_handled;
$sql = ("SELECT SUM(swap) AS sum_swap FROM production WHERE Datum = '$actual_time' AND jaar = '$year' ");
$result = mysqli_query($connect, $sql) ;
$swap = $result->fetch_object()->sum_swap;
答案 0 :(得分:5)
您可以使用多个SUM(示例基于预准备语句):
SELECT SUM(`Case_closed`) AS `sum_closed`, SUM(`Case_handled`) AS `sum_handled`, SUM(`swap`) AS `sum_swap`
FROM `production`
WHERE `Datum` = ?
AND `jaar` = ?
Little Bobby说your script is at risk for SQL Injection Attacks.了解prepared的MySQLi语句。即使escaping the string也不安全!
答案 1 :(得分:0)
通过跟随@little Bobby他的建议找到了解决方案来做一个准备好的声明,但是我没有参加专栏。它目前设置为($type)
,但我希望(?)
function resultaten($type){
$connection = mysqli_connect("localhost","root","","dbname");
if(mysqli_connect_errno()){
echo mysqli_connect_error();
exit();
}
$query = ("SELECT SUM($type) AS sum_gesloten FROM productie WHERE Datum=? AND jaar=?");
$time = time();
$actual_time = date('d-m-Y', $time);
$year = date("Y");
$stmt = mysqli_prepare($connection,$query);
if($stmt){
mysqli_stmt_bind_param($stmt, 'ss', $actual_time, $year);
mysqli_stmt_bind_result($stmt, $typeresult);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
if(!empty($type)){
echo "$type $typeresult";
}else{
echo "No results!";
} }else{
echo "Error creating statement object!";
}
}
$ Case_gesloten = resultaten(' Case_gesloten'); echo $ Case_gesloten;