I have created a query which seems to execute with no errors. I am getting the total of two columns in two different fields related to one customer, I only want to retrieve the data which was within the past year.
I have used this but it seems to throw all the data stored.
$yearago = (date('Y')-1).date('-m-d');
$sumtotal = $adb->pquery("SELECT
SUM(currentamount),
SUM(newcurrentamount),
(SUM(currentamount) + SUM(newcurrentamount)) as 'Total'
FROM vtiger_addisa, vtiger_isa
WHERE vtiger_addisa.addrelatedclient = $relatedclient
AND vtiger_isa.relatedclient = $relatedclient
AND vtiger_isa.startdate >= $yearago
");
$sumtotal->fetchInto($row);
$clientotal = $row['Total'];
echo $clientotal;
//print_r($sumtotal);
Related
I have a database which holds two timestamps (date_ticket_reported, date_ticket_resolved), I want to caluclate the average time difference between these times for each resolved_by user_id.
Each row has a (resolved_by) column which corresponds to a user_id.
There will be multiple rows, for each user_id.
I have tried various approaches including the following.
ticket_model.php code
public function get_resolved_time_by_user($user_id){
$query1 = $this->db->select('resolved_date')->from('tickets')->where('resolved_by',$user_id)->get();
$resolved1 = $query1->row();
$query2 = $this->db->select('ticket_date_reported')->from('tickets')->where('resolved_by',$user_id)->get();
$reported1 = $query2->row();
$resolved2 = $resolved1->resolved_date;
$reported2 = $reported1->ticket_date_reported;
foreach($resolved2 as $row){
//Convert them to timestamps
$reported_dateTimestamp = strtotime($resolved2);
$resolved_dateTimestamp = strtotime($reported2);
$diff = $resolved_dateTimestamp - $reported_dateTimestamp;
return $diff;
}
}
Ticket view code
<p> Average Resolve Times <?php echo $this->ticket_model->get_resolved_time_by_user($user_id); ?> </p>
So to summarise; I want to display the average time between date_ticket_reported, date_ticket_resolved. For each user_id specified.
Any help would be awesome!
I have tried Malkhazi Dartsmelidze answer,
$this->db->query("SELECT
AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as timediff,
resolved_by as user
FROM tickets
GROUP BY resolved_by");
I get an error saying Object of class CI_DB_mysqli_result could not be converted to string
Where you say resolved_by as user. Should "user" be the user_id? ie should it say "resolved_by as user_id"?
You Can run only One Query With Myqsl:
SELECT
AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as timediff,
resolved_by as user
FROM tickets
GROUP BY resolved_by
This returns Average Time Difference in Seconds for Each User
Try this
$resolved2 = $resolved1->resolved_date;
$reported2 = $reported1->ticket_date_reported;
$diff = $resolved2 - $reported;
And then echo $diff and check what you are getting in $diff,
I'm trying to update multiple cells in a MySQL database based on a previous update date. I am having an issue with unchanged, trailing cells updating to 0.
Database table looks like this (default = 0 for Day#; N = last update date):
id--Run--Day1--Day2--Day3--Day4
1----N------1-----2-----3----4
The code below does the following:
Retrieves the database entry under column= Run, id=1
Subtracts that date from today's date.
Uses that difference to move database for Day1->Day4 to the left.
Example database table when the difference is 2 days:
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----3----4
My issue is that I need it to change all trailing Days to 0. So in this example, Day3 & Day4 should both be 0.
I've been trying out another foreach() statement within but can't get the logic behind it. Would someone please point me in the right direction?
$DaysColumnRange2 = range (1, 4);
foreach ($DaysColumnRange2 as $DaysColumnRangeLoop2){
$SubtractedDaysColumns2 = $DaysColumnRangeLoop2 - $diff2format;
$MoveToNewDay2 = ${$Day.$SubtractedDaysColumns2};
$OriginalOldDay = $diff2format + $SubtractedDaysColumns2;
$sql2 = "UPDATE users SET Day$MoveToNewDay2='$OriginalOldDay' WHERE id='$id'";
if ($conn->query($sql2) === TRUE) {
echo "RECORDS UPDATED SUCCESFULLY";
} else {
echo "Error updating record: " . $conn->error;
}
}
I'll update this first post with my attempts as I continue to work on it.
(this is not a great way of doing it, but this is what I was able to put together since Cron jobs wasn't reliable & I haven't yet figured out how MySQL Triggers work)
**
------------------UPDATE--------------
**
This section is to clarify my question.
Let's say this is my database right now:
id--Run--Day1--Day2--Day3--Day4
1----N------1-----2-----3----4
I run the code below where $diff2format = 2:
//>Database credentials + login here
//Retrieve database entry for Run
$id = 1;
$todaysdateupdate = date("Y-m-d");
$lastupdatequeryresult = mysql_query("SELECT Run FROM users WHERE id='$id'");
$lastupdaterow = mysql_fetch_assoc($lastupdatequeryresult);
//Compare Run date to today's date.
$date3=date_create($lastupdaterow['Run']);
$date4 = date_create(date("Y-m-d"));
$diff2=date_diff($date3,$date4);
$diff2format = $diff2->format("%a");
//Day1, 2, 3, etc...
$result1 = mysql_query("SELECT Day1 FROM users WHERE id='$id'");
$row1 = mysql_fetch_assoc($result1);
//Hard coded "Day#" variables
$Day = "Day";
$Day1 = $row1['Day1'];
$Day2 = $row2['Day2'];
$Day3 = $row3['Day3'];
$Day4 = $row4['Day4']; //etc
//MY QUESTION STARTS HERE****************
$DaysColumnRange2 = range (1, 4);
foreach ($DaysColumnRange2 as $DaysColumnRangeLoop2){
$SubtractedDaysColumns2 = $DaysColumnRangeLoop2 - $diff2format;
$MoveToNewDay2 = ${$Day.$SubtractedDaysColumns2};
$OriginalOldDay = $diff2format + $SubtractedDaysColumns2;
$sql2 = "UPDATE users SET Day$MoveToNewDay2='$OriginalOldDay' WHERE id='$id'";
if ($conn->query($sql2) === TRUE) {
echo "RECORDS UPDATED SUCCESFULLY";
} else {
echo "Error updating record: " . $conn->error;
}
}
The output for the database is below. Basically it copied Day3 moved it 2 times to the left, then copied Day4 and also moved 2 times to the left. Nothing changed with Day3 or Day4.
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----3----4
But I need it to output this instead:
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----0----0
Hi buddies :) I was required to create a php code to handle some workers' data stored in DB. I got the desired result but it takes seconds and seconds (seconds and seconds! >.<) to finish, so I'm afraid I'm not doing something in a right way :(
The workers' data is stored in a mysql table (table1), something like this:
I'm given a pair of dates: initial_date (a) and final_date (b), so my goal is to copy the given workers' data in a new table (table2), day by day from a to b. The expected table should be as shown below (this table will be used later as a basis for further operations, which is not part of the question)
It's a requirement to overwrite any existing data between a and b dates, and 'jump' weekends and holidays.
To get my goal, I'm coding this (let's assume that the connection and all that is done and the checkworkingday function is given):
$initialdate = '2016-10-10';
$finaldate = '2016-10-12';
$x = $initialdate;
do {
if (checkworkingday($x) == true) {
$query = mysqli_query($connection,"SELECT name,task FROM table1");
while($row = mysqli_fetch_array($query)) {
$task = $row['task'];
$worker = $row['name'];
$query2 = mysqli_query($connection,"SELECT task FROM table2 WHERE name = '$worker' AND date = '$x'");
$row2 = mysqli_fetch_array($query2);
$existingtask = $row2['task'];
if (!isset($existingtask)) {
mysqli_query($connection,"INSERT INTO table2 (date,name,task) VALUES('".$x."','".$worker."','".$task."')");
} else {
mysqli_query($connection,"UPDATE table2 SET task = '".$task."' WHERE date = '".$x."' AND worker = '".$name."'");
}
}
}
$x = date('Y-m-d', strtotime($x . "+1 day"));
} while ($x <= $finaldate);
Just for 3 days as shown in the example, it takes a long to end; and for several weeks or months it takes very, very long (even max execution time is exceeded depending on dates range!).
I'm a newbie and I know the code is quite 'rustic', but I've revised and checked the code and info out there without getting a better performance. What am I doing wrong? Thanks :)
Instead of looping through the enitre data, try INSERT.. SELECT :
INSERT INTO table2 (date,name,task)
SELECT date,name,task
FROM Table1
WHERE < >;
Already solved. I just used WHERE MONTH(due_date) = $month in the SQL clause. Never knew it would just be like that. Thank you for all your answer!
We have a table called bills. We do not delete a bill even if it is paid already for record purposes.
So our goal is to only display The Bills for this Month. I have a $cur_month = current month value. I know how to extract the month value from a field using MONTH(), using a loop to run though the table, but when I try to echo MONTH(date) the value through out the displayed series is just the MONTH VALUE of the very first row. It seems it failed to get the MONTH VALUE of the other rows.
Fixed code below
$query = "SELECT * FROM bill WHERE MONTH(due_date)=$month";
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC))
{
$bdata = mysql_fetch_assoc(mysql_query("SELECT MONTH(due_date) AS M FROM `bill`"));
if($bdata['M'] == $month)
{
echo "<tr>";
echo "<td>".$brow['room_id']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
}
$month there is the holder of the current month
$bdata['M'] there is the holder of the month extracted. We just displayed it to check.
So if extracted_month is equls to current_month then display bill
I hope you can help me in this.
PS: Still an amateur. This is not yet an online website. We only need help for the purpose of having it work.
1) Use a WHERE statement in your first SQL to only fetch those rows from the table.
Like this:
$query = "SELECT *, MONTH(due_date) as M FROM bill WHERE MONTH(due_date)=" . $month;
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>".$brow['M']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
2) I find it good practice to always check if the result object is created and if so, to check if it returned matches (with mysql_num_rows($result)). That way you can show an error if something goes wrong (most likely in the SQL statement) or show the user that there are no matches (bills in this case).
3) Try to use MYSQLI to connect to your database instead of MYSQL, since the latter is deprecated. (See: http://php.net/manual/en/mysqli-result.fetch-assoc.php for an example.)
Try solving this problem using SQL.
SELECT b.amount_paid
FROM bills b
WHERE MONTH(b.due_date) = 3
Using the result of this query you would have all of the amounts for this month. Sum your result and you are done.
i this problem that i am sure are very simple to some people but atm i just cant wrap my head around it.. here goes i want to plus all data outputs from a certain row with the code i have now it just outputs for example 12 2 12 14 but i want to get 40 instead of the above just to state a example here is my code
$searchTimeScale = mysql_query("SELECT * FROM workhours WHERE case_project_id='$myCaseId'");
while($timeFeed = mysql_fetch_assoc($searchTimeScale)){
$workedHours = $timeFeed['worked_hours'];
$workedMinutes = $timeFeed['worked_minutes'];
echo $workedHours;
var_dump($workedMinutes);
}
You should use aggregate function SUM() along with GROUP BY
SELECT SUM(your_hour_field)
FROM workhours
WHERE case_project_id='$myCaseId'
GROUP BY case_project_id
You don't technically need GROUP BY here since you are only querying for a single case_project_id, but I am showing it in case you ever wanted to SUM up across a full record set with aggregations on a specific field or fields.
You can aggregate in your SQL query by selecting SUM(worked_hours*60+worked_minuts). That gives you the total number of minutes.
Just keep a counter going:
$total = 0;
while($timefeed = mysql_fetch_assoc(...))) {
$total += ($timeFeed['worked_hours'] * 60) + $timeFeed['worked_minutes'];
}