Mysql query shows date results a little mixed up - mysql

I'm trying to get a minimum and maximum temperature from a database for each day.
But he retrieves the date year in wrong order I get values like this:
Array ( [00-00-0000] => 22 [00-08-2013] => 22 [01-08-0201] => 24 [01-08-0213] => 24 [01-08-2013] ...
if I verify the data from the table with PHPmyAdmin everithing seems ok.
code:
$query = "SELECT DATE_FORMAT(`Datum`, '%d-%m-%Y') as Datum1, min(`Temperatuur`)as minTemp ,max(`Temperatuur`)as maxTemp FROM `tableGreenhouse` GROUP BY `Datum1` ORDER BY 1";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$date = $row['Datum1'];
$Temp1 = $row['minTemp'];
$Temp2 = $row['maxTemp'];
$dataArray1[$date]=$Temp1;
$dataArray2[$date]=$Temp2;
}
}
print_r($dataArray1);
print_r($dataArray2);

There doesn't appear to be anything wrong with your query.
Maybe you could try casting the variables to a certain type using the following code:
if ($result->num_rows > 0) {
// In some cases, code breaks if you do not do this...
// Experienced it myself a few times.
$dataArray1 = array();
$dataArray2 = array();
while($row = $result->fetch_assoc()) {
/* For error checking, enable following statement: */
// var_dump($row);
$date = (string)$row['Datum1'];
$Temp1 = (float)$row['minTemp'];
$Temp2 = (float)$row['maxTemp'];
$dataArray1[$date]=$Temp1;
$dataArray2[$date]=$Temp2;
}
}

Related

PDO query returns multiple arrays. How to uniquely identify them?

This query returns 13 individual arrays:
$array = array($pgff_id, $pgfm_id, $pgmf_id, $pgmm_id, $mgff_id, $mgfm_id, $mgmf_id, $mgmm_id, $pgf_id, $pgm_id, $mgf_id, $mgm_id, $fid, $mid);
foreach($array as $id) {
$stmt = $db->prepare("SELECT birth_year, death_year FROM index WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
print_r shows that they look like this:
Array ([birth_year] => 1750 [death_year] => 1824)
Array ([birth_year] => 1770 [death_year] => 1836)
... etc
Is it possible to assign a number or name to these individual arrays? The results are not useful without a way to identify them.
I tried doing it like shown below. This way does number the arrays but orders the results as they are found in the table. I really need the results ordered as they are in $array (which the first method does manage).
$in = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$data = $stmt->fetchAll();
Taking your code and adding in id as an expression in the query would result in this:
$in = str_repeat('?,', count($array));
$sql = "SELECT id, birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo "here starts another row:<br>";
echo "id = ".$row["id"]."<br>";
echo "birth_year = ".$row["birth_year"]."<br>";
echo "death_year = ".$row["death_year"]."<br>";
}
So, that's how you can access it.
You can rearrange the data in the rows after you've received them from the database, again by using a foreach loop:
$birth = [];
$death = [];
foreach ($rows as $row) {
$id = $row["id"];
$birth[$id] = $row["birth_year"];
$death[$id] = $row["death_year"];
}
Now you can access both arrays to get the birth or death year based on the id like this:
echo $birth[4]. 'and '. $death[4];
where id is 4.

how to get the number of rows in mysql statements and return it?

I am currently having problem getting the number of rows in my code. here's my code:
$app->get('/banana/:state', function($state) use ($app){
$db = new DbOperation();
$today = date("j-M-Y");
if($state == "Indoor"){
$result = $db->getAllbananaindoor($today);
$response = array();
$response['messages'] = array();
$row = $result->fetch_assoc();
if($row > 3){
$temp = array();
$temp['text'] = 'Yes, you can plant banana seeds today indoors.';
array_push($response['messages'],$temp);
}
else {
$temp = array();
$temp['text'] = 'Nope. Today is not a good time to plant banana seeds indoors.';
array_push($response['messages'],$temp);
}
echoResponse(200,$response);
}
}
public function getAllbananaindoor($today){
$stmt = $this->con->prepare("SELECT * FROM garden WHERE humid >? AND time=? AND temp BETWEEN ? AND ?");
$hum = '50';
$one = '19';
$two = '24';
$stmt->bind_param("iiii",$hum, $today, $one, $two);
$stmt->execute();
$students = $stmt->get_result();
$stmt->close();
return $students;
}
In this I get the database data from a function getAllBananaindoor() which returns the result instead i want it return the number of rows and finally check whether $row is greater than 3 and then work on that. how can I do that? please help.
The MySQLi Result object has num_rows property defined.
$students = $stmt->get_result();
return $students->num_rows; // will return the number of rows

Get maximum value of row in mysql ,using codeigniter

Get maximum value of row in mysql using codeigniter.
i have following mysql data
I need to get the details based on total_payment of each student.
like this
i tried code below
$student_id_dis = $this->db->query('SELECT DISTINCT(student_id) FROM student_fees')->result_array();
$fee_cat_id_dis = $this->db->query('SELECT DISTINCT(fee_category_id) FROM student_fees')->result_array();
$this->db->select(['student_fees.*', 'fee_categories.fee_category_name as fee_name', 'fee_categories.amount as fee_amount']);
$this->db->join('student', 'student_fees.student_id = student.student_id');
$this->db->join('fee_categories', 'student_fees.fee_category_id = fee_categories.fee_categories_id');
$where = '';
for ($i = 0; $i < count($student_id_dis); $i++) {
if (isset($fee_cat_id_dis[$i]['fee_category_id'])) {
$where .='total_paid = (SELECT max(stdp.total_paid)
FROM student_fees stdp
WHERE stdp.fee_category_id = ' . $fee_cat_id_dis[$i]['fee_category_id'] . ')';
}
$this->db->where($where);
$this->db->get('student_fees')->result_array();
}
try this
select * from student_fees where student_fees_id in
(select student_fees_id from
where total_paid =max(total_paid) group by fee_category_id)

How do I get DateTime from mysql and set it to json format ready for highcharts

I started my project March last year and have almost got it right.
Trying to get data from mysql and put it in highcharts.
This is my query
<?php
$con = mysqli_connect("localhost","root","root","manortsc_test");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sth = mysqli_query($con,"
SELECT DateTime,max(T)
FROM alldata
WHERE DATE(DateTime) = CURDATE() - INTERVAL 1 DAY
GROUP BY hour(DateTime)
"
);
$rows = array();
$rows['name'] = 'Outside';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['max(T)'];
}
$result = array();
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
The json output is missing the date and time
[{"name":"Outside","data":[17.5,16.3,15.6,15.1,14.4,14,14.1,16,18.5,21.7,24.1,26.9,28.3,29.6,30.6,31.1,31.8]}]
The graph shows okay (except datetime on x axis) and I cannot figure how to fix it. I have tried every way except the correct way. Any help would be appreciated.
Changed the query to this and now it works.
Thanks wergeld and Yuri for the assistance.
$sth = mysqli_query($con,"
SELECT DateTime,max(T)
FROM davisvp
WHERE DATE(DateTime) = CURDATE()
GROUP BY hour(DateTime)
"
);
$result = array();
$result['name'] = 'temperature';
while($row = mysqli_fetch_array($sth))
{
$date = strtotime($row['DateTime']);
$maxt = 1 * $row['max(T)'];
$result1 = array();
array_push($result1,$date);
array_push($result1,$maxt);
$result['data'][] = $result1;
}
echo json_encode($result, JSON_NUMERIC_CHECK);

mysql array selecting and sum values

I own an array that three records containing:
value datetime
2 03/03/2015 14:34:00
4 03/03/2015 14:36:00
5 03/03/2015 13:34:00
I want to select the records that are on time 14 and sum them. In the above example would be 4 + 2 = 6
How can I do this?
$sql ="SELECT amperagem, data FROM tomada WHERE date(data) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";//
mysql_select_db('localiza');
$retval = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($retval);
while($row = mysql_fetch_array($retval, MYSQL_BOTH)){
$hour= substr(($row['data']),11, 2);
The sql is as simple as:
select sum(value) from tomada where hour(datetime) = 14;
You can actually get yourself the value through a single SQL query:
Be sure to read up on http://www.w3schools.com/sql/func_datepart.asp
So to get all records with a datetime containing 14:XX:XX
SELECT value FROM tomada WHERE HOUR(data) = 14;
Now simply get the rows like you did and retrieve the 'value' per row and add them up
$res = mysql_query( $sql, $conn );
$returnObjects = array();
if ($res == null) {
return $returnObjects;
}
while(!is_null($row = mysql_fetch_row($res))){
$returnObjects[] = $row;
}
$returnArray = mysql_fetch_array($returnObjects);
$sum = 0;
for($row = 0, $size = count($returnArray); $row < $size; $row++){
$sum += $returnArray[$row][0]; //Note 0 is the value you need
}
return $sum;
Note it can be done in less lines of codes with less steps but I find this helps reading what i'm doing. Also some additional checks if certain objects are NULL or values are invalid is recommended.