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.
Related
Please forgive if already answered. I have looked at lots of other questions and none are helping! Basically, I want to copy a single row from one table, to another table. The problem I have struck, is the the id of the row I want to copy, is already in use, in the table I want to copy to. This is what I have at present, it works, until it strikes this problem.
INSERT INTO venues SELECT * FROM submitted_venues WHERE id='9';
It generates the error: Duplicate entry '9' for key 'id'
Is there a way to change the id number on the fly, so that it create an unused new number for the receiving table, or do I have to write a query that names and gets all of the fields for each table. Some thing like the replace statement 0 cases would be good, where 0 creates a new record!!
The 9, is just a number that I used for this example, of course it changes.
EDIT:
I have created a work around for this problem.
//get highest id number of table to copy to
$sql = "SELECT id FROM venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$to_id = $row[ 0 ];
//increase id
$to_id ++;
//get highest id number of table to copy from
$sql = "SELECT id FROM submitted_venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$from_id = $row[ 0 ];
//increase id
$from_id ++;
//get highest unused id number
$temp_id = $to_id > $from_id ? $to_id : $from_id;
//update existing record to ensure that its id number will not conflict
$sql = "UPDATE submitted_venues SET id = '$temp_id' WHERE id='$current_venue_id'";
if( $result = mysqli_query( $mysqli, $sql ) ){
$current_venue_id = $temp_id;
//copy record to normal regular venues table
$sql = "INSERT INTO venues SELECT * FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not copy -> " . mysqli_error($mysqli) );
//delete record from temp db table
$sql = "DELETE FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not delete -> " . mysqli_error($mysqli) );
}
}
}
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)
Bit of a noob when it comes to PDO. We have a a table that needs to be updated with a cron job daily. The idea is to query the table and for each "active = 1" get an integer from a duration column convert that into days, get the "expiration" column and the duration to the expiration and update the expiration.
I am not even close to getting this to work, I am trying to just get the basics for now. Return the duration which is in hours divide by 24 add that to the date column as days and update EACH row with the appropriate new time.
The problem is I do not know how to update each row with its own information. I have the code below, it updates each row but the new "expires" date ends up being the same even though the expires values are different.
static function cronSetFeatured(){
try{
$db = new PDO('mysql:host=127.0.0.1;dbname=mydb', 'dbuser', 'pw' );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
die();
}
$query = $db->query('SELECT * FROM featured_producers ');
$now = date('Y-m-d H:i:s');
while($r = $query->fetch(PDO::FETCH_OBJ)){
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
}
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != 0";
$q = $db->prepare($sql);
$q->execute(array($expires));
echo $expires.'<br>';
}
Well if you want to UPDATE each record on its own, that query need to be part of the loop body:
while($r = $query->fetch(PDO::FETCH_OBJ)){
//calculate expiration
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
//Get the id (needed for update)
$id = $r->id;
//updating
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != ?";
$q = $db->prepare($sql);
$q->execute(array($expires, $id));
echo $expires.'<br>';
}
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;
}
}
I have two set of arrays in different MYSQL table. This what I want to do
What I Want TO Do
TABLE_ONE connect to the table.
get the value we want from session_id
THEN get the array associated with the value (session_id)
explode the array to get individual values.
NOW::::: - GO TO TABLE_TWO
TABLE_TWO Go straight to the first value from array (TABLE_ONE)
Explode the array associated with it.
Delete the number that's equal to the session_id
_____________________________________________________
And so fort....
More visual explanation below:
session_id = 4
TABLE_ONE:
id array1
1 4
2 1
3 2,5
4 1,3,4,5
5 4,5
TABLE_TWO:
id array2
1 4,6,9,2
2 3,7,8,2
3 7,12,4,9
4 1,5,4,8
5 3,6,12,3,5,4
So, because session_id = 4, we go to TABLE_ONE id 4. The array of id-4 is 1,3,4,5.
So now we know 4 can be found in id 1,3,4,5 of TABLE_TWO
We should now explode TABLE_TWO's array and delete 4 from there array. Implode the array and save the new value to database.
THIS IS WHAT I HAVE DONE - it would delete only '4' from them id-3 and delete all the values in id-4. Please help!!
$SESSION = 4;
$depSQL = mysql_query("SELECT array1 FROM TABLE_ONE WHERE id='$SESSION' LIMIT 1");
while($row=mysql_fetch_array($depSQL)) { $depARRAY = $row["array1"]; }
$explodedDEP = explode(",", $depARRAY);
foreach ($explodedDEP as $key1 => $value1) {
$stSQL = mysql_query("SELECT array2 FROM TABLE_TWO WHERE id='$value1'");
while($get=mysql_fetch_array($stSQL)) { $stARRAY = $get["array2"];}
$explodedST = explode(",", $stARRAY);
foreach ($explodedST as $key2 => $value2) {
if ($value2 == $SESSION) {
unset($explodedST[$key2]);
}
}
$newST = implode(",", $explodedST);
$sql = mysql_query("UPDATE TABLE_TWO SET array2 ='$newST' WHERE id='$value2'");
}
exit();
Please help!!! I'm really struggling on it.
I have tried it for hours now and i havent really got any where.
I think the problem is with the inserting to database.
Please help.
You can avoid one loop by using the array1 in your second SQL directly since it is already a comma seperated list.
Try this:
EDIT: Updated the code after testing.
$SESSION['ID'] = 4;
$depSQL = mysql_query("SELECT array1 FROM TABLE1 WHERE id='".$SESSION['ID']."' LIMIT 1");
while($row=mysql_fetch_array($depSQL))
{
$depARRAY = $row["array1"];
}
$stSQL = mysql_query("SELECT id, array2 FROM TABLE2 WHERE id IN ($depARRAY)") or die("Query Error");
while($get=mysql_fetch_array($stSQL)) {
$stARRAY = $get["array2"];
$id = $get["id"];
$explodedST = explode(",", $stARRAY);
foreach ($explodedST as $key2 => $value2) {
if ($value2 == $SESSION['ID']) {
unset($explodedST[$key2]);
}
}
$newST = implode(",", $explodedST);
echo $id . " " . $newST . "<BR/>" ;
$sql = mysql_query("UPDATE TABLE2 SET array2 ='$newST' WHERE id='$id'");
}
exit();
$SESSION is an array you can not assign value like this $SESSION = 4;
assign value like this
$SESSION['id'] = 4;
if ($value2 == $SESSION['id']) {