我有一个php结果页面,它从提交的php表单中获取值,如
$sales = mysqli_real_escape_string($link, (int)$_POST['sales']);
我有一个插入查询
$sql = "INSERT INTO daily (date, sales) VALUES (CURRENT_TIMESTAMP, '$sales')";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
现在我想向db添加一个额外的字段,该字段将基于新的选择查询
$query = "SELECT SUM(sales) FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
我试图将它添加到插入sql而没有结果
$sql = "INSERT INTO daily (date, sales, total_sales) VALUES (CURRENT_TIMESTAMP, '$sales', '$query')";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
答案 0 :(得分:3)
您可以使用插入/选择
$sql = "INSERT INTO daily (date, sales, total_sales)
SELECT
CURRENT_TIMESTAMP,
'$sales',
SUM(sales)
FROM daily
WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
分两步你可以执行你的查询获取值并分配给插入...例如:
$query = "SELECT SUM(sales) as tot FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
mysqli_query($link, $query) ;
$row = mysql_fetch_array($result, MYSQL_NUM);
$myTotal = $row[0]
$sql = "INSERT INTO daily (date, sales, total_sales) VALUES (CURRENT_TIMESTAMP, '$sales', '$myTotal')";
答案 1 :(得分:0)
您应首先运行该查询,将结果保存在数组中,遍历数组并将结果添加到数据库的正确字段中。
您现在正在做的是在total_sales
表的daily
列中添加查询文字。
你可以参考这个答案来激励自己:Get sum of MySQL column in PHP
此外,this页面非常清楚地说明了您需要做什么,向下滚动,直到您到达标题为“#34;将查询结果插入到另一个表格中的组合”#34;
答案 2 :(得分:0)
有效的代码很简单:
$result= mysqli_query($link, "SELECT SUM(sales) as valuesum FROM daily);
$row = mysqli_fetch_assoc($result);
$total_sales = $row['valuesum'];
我无法管理它,因为我从phpfpm-error.log找到了其他错误
答案 3 :(得分:-1)
尝试这种方式:
$sales = mysqli_real_escape_string($link, (int)$_POST['sales']);
$query = "SELECT SUM(sales) FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'"
$sql = "INSERT INTO `daily` SET `date` = CURRENT_TIMESTAMP, `sales` = ' ".$sales." ', `total_sales` = ($query)";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}