본문 바로가기
PHP

sql 데이터 가져오기 객체while , 배열for문

by sj0020 2021. 9. 29.

while로 가져오기

객체..

$today = date("Y-m-d");

$week_day1 = date("Y-m-d", (strtotime('-1 days', time())));
$week_day2 = date("Y-m-d", (strtotime('-2 days', time())));


$sql = "SELECT ROUND(avg(convert(float,temp)),2) AS  'temp',
ROUND(avg(convert(float,humidity)),2) AS  'humidity',
ROUND(avg(convert(float,water)),2) AS  'water',
ROUND(avg(convert(float,cdc)),2) AS  'cdc',
LEFT(date_time,10) as 'date_time' 
FROM dbo.sensor 
WHERE LEFT(date_time,10) IN ('$today','$week_day1','$week_day2') 
GROUP BY left(date_time,10)";


// 1. 데이터베이스에서 데이터를 가져옴
if ($result = sqlsrv_query($con, $sql , $params, $options)) {
    // 2. 데이터베이스로부터 반환된 데이터를
    // 객체 형태로 가공함
    $o = array();
    while ($row = sqlsrv_fetch_object($result)) {
        $t = new stdClass();
        
        $t->temp = $row->temp;
        $t->humidity = $row->humidity;
        $t->cdc = $row->cdc;
        $t->water = $row->water;

        $t->date_time = $row->date_time;


        $o[] = $t;
        unset($t);
    }
} else {
    $o = array( 0 => 'empty');
}


print_r($o)

결과

 


for 문 가져오기


$today = date("Y-m-d");

$week_day1 = date("Y-m-d", (strtotime('-1 days', time())));
$week_day2 = date("Y-m-d", (strtotime('-2 days', time())));
$week_day3 = date("Y-m-d", (strtotime('-3 days', time())));
$week_day4 = date("Y-m-d", (strtotime('-4 days', time())));
$week_day5 = date("Y-m-d", (strtotime('-5 days', time())));
$week_day6 = date("Y-m-d", (strtotime('-6 days', time())));

$sql_week = "SELECT ROUND(avg(convert(float,temp)),2) AS  'temp',
	ROUND(avg(convert(float,humidity)),2) AS  'humidity',
	ROUND(avg(convert(float,water)),2) AS  'water',
	ROUND(avg(convert(float,cdc)),2) AS  'cdc',
	LEFT(date_time,10) as 'date_time' 
	FROM dbo.sensor 
	WHERE LEFT(date_time,10) IN ('$today','$week_day1','$week_day2') 
	GROUP BY left(date_time,10)";

$result_week = sqlsrv_query($con,$sql_week,$params,$options);
$total_week = sqlsrv_num_rows($result_week);

$temp_arr = array();
$water_arr = array();
$hum_arr = array();
$date_arr = array();
$cdc_arr = array();
for ($i=0; $i < $total_week; $i++) {
	$row_week = sqlsrv_fetch_array($result_week);
	$temp = $row_week['temp'];
	$humidity = $row_week['humidity'];
	$water = $row_week['water'];
	$date_time = $row_week['date_time'];
	$cdc = $row_week['cdc'];
	array_push($temp_arr,$temp);
	array_push($hum_arr,$humidity);
	array_push($water_arr,$water);
	array_push($date_arr,$date_time);
	array_push($cdc_arr,$cdc);

}