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,
Related
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'];
}
I am pulling 5 entries from a database, which is working fine. I then do some math for each entry to get different numbers. Those 5 numbers will show up next to eachother. I need to put those 5 entries into an array, and then select the average of those 5, so I just have one solid number.
From the mysql_fetch_array, I pulled $last_score, $blue_rating, and $blue_slope for the latest 5 entries. Now here is where I'm at:
$query_p1 = "SELECT * FROM scorecards WHERE player_id='$player_id' LIMIT 5";
$result_p1 = mysql_query($query_p1);
while ($row_p1 = mysql_fetch_array($result_p1)) {
$blue_rating = $row_p1["blue_rating"];
$blue_slope = $row_p1["blue_slope"];
$last_score = $row_p1["total_score"];
$handicap = (((($last_score - $blue_rating) * 113) / $blue_slope) * .96);
echo "$handicap <br>";
}
Those 5 echo's are what I need in a single array with the average of the 5. Any help would be much appreciated. Thank you.
Instead of
echo "$handicap <br>";
Put
$handicaps[]= $handicap;
Then outside the loop you could do
echo array_sum($handicaps)/5;
wondering if it is possible, that when you search a list of pages and data from a site, if you can not only order them in the most related first, but to also show a value.
ex. you search for data you previously entered regarding lemonade you sold. you keep track of multiple factors like "time of day, temperature, month, etc." you want to know about how much you are going to sell a week later, so you punch in values to "time of day, temperature, month, etc."
In theory, i am hoping to be able to bring up all entered data in accordance to relevance, and it shows you an estimate of what you will sell based on previous records. Any ideas?
Thanks
It would require an algorithm. i wont write all the code, but i wont mind giving some guidance :).
The html to fetch the data would be the same as the html to set the data, except it will call a seperate .php script.
The example below can be used for guidance. It uses only temperature to calculated predicted sales:
//get todays temperature from form, and query database for all temperatures
$todaysTemp = $_POST['temperature'];
$tempRange = 20; //each temperature in the table must be within this range of todaysTemp to be included in calculation
$result = $connection->query("SELECT temperature, sales FROM myTable");
//calculate average temperature by adding this temp to total, then diving by total rows included
$temp_sales_array = array();
foreach($result as $row){
if( abs($todaysTemp - $row['temperature']) < tempRange){
$temp_sales_array[$row['temperature']] = $row['sales'];
}
}
//calculate predicted sales, by getting array value thats closest to todays temperature
$closest=key($temp_sales_array[0]);
foreach($temp_sales_array as $row){
if( abs($todaysTemp - key($row)) < closest ){
closest = key($row);
$predicted_sales = $row;
}
}
//show predicted sales
echo $predicted_sales;