我想从单个表中获取2行数据,结果我想显示为单行数据

时间:2019-12-27 06:18:02

标签: php mysql

  

这是称为vehicle_data的表   vehicle table

     

并且我想在单行数据(如

)中计算两行相同 日期数据
SELECT * FROM vehicle_data WHERE `date` = '2019-12-27'

enter image description here

session_start();
require('../db_config.php');
$date= date('Y-m-d');
$date = $_GET['date'];
$sql = "SELECT * FROM vehicle_data WHERE `date` = '$date' AND `camera_id`=1,2";
$result = $conn->query($sql); 

while($row = $result->fetch_assoc()) {


$myObj->bicycle = $row["bicycle"];
$myObj->motorcycle = $row["motorcycle"];
$myObj->wheeler_3_4 = $row["wheeler_3_4"];
$myObj->seden_car = $row["seden_car"];
$myObj->pick_up = $row["pick_up"];
$myObj->mini_bus = $row["mini_bus"];
$myObj->boro_bus = $row["boro_bus"];
$myObj->covered_van = $row["covered_van"];
$myObj->all_truck = $row["all_truck"];
$myObj->trailor_truck = $row["trailor_truck"];
$myObj->total_vehicle = $row["total_vehicle"];

$myJSON = json_encode($myObj);
echo $myJSON;

}

  

请指导我,谢谢。

1 个答案:

答案 0 :(得分:1)

只需使用SELECT SUM

$pdo = new PDO('mysql:dbname=myscript;host=localhost','root','', $opt);

$sql = "select date, SUM(bicycle) AS bicycle,  SUM(motorbicycle) AS motorbicycle, ...
from vehicle_data
where `date` = :date AND `camera_id`=1,2"

$stmt = $pdo->prepare($sql);
$stmt->execute(['date' => $date]);
$data = $stmt->fetch();

不要只是将变量放在原始sql中,请使用bindParam防止SQL注入。而且PDO更好。