Get database output as one - php

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'];
}

Related

Sums data from an array that has the same id

I have a query about this project that I am doing, I make a query to my two tables and the data that I call in this case is a quantity number for both, the data displayed is the one that has the same id for both tables.
The problem occurs when I pass two identifiers and to those two identifiers I want to add their current amount with the amount obtained from the other table
In general, what I want to do is add the amounts obtained, this is my code that I am working with, I would really appreciate if you can help me solve it or guide me.
$id_servis = [1077,1078];
$sum_quantity_add = Servis_tareas::where('servis_id',$id_servis)->get();
foreach($sum_quantity_add as $sum_add){
$quantity_two[] = $sum_add->quantity;
}
$quantity_actual = Servis::wherein('id',$id_servis)->get();
foreach($quantity_actual as $quantity_act){
$quantity_one[] = $quantity_act->quantity_final;
}
dd($id_servicios,$quantity_one, $quantity_two);
//ERROR
$total[] = $quantity_one + $quantity_two;
//ERROR
if(is_numeric($total) < 0 ){
Servis::wherein('id',$id_servis)->update(['quantity_final' => 0]);
}else{
Servis::wherein('id',$id_servis)->update(['quantity_final' => $total]);
}
In MySql/SQL there is SUM query which handles the addition and they are called Aggregation Functions, and in Laravel there is a Eloquent equivalent of these Laravel Aggregates, using these methods you will be able to count, max, min, avg on the query end rather than in the PHP end.
So, your code will look like
$id_servis = [1077, 1078];
$sum_quantity_add = Servis_tareas::where('servis_id', $id_servis)->SUM('quantity');
$quantity_actual = Servis::wherein('id', $id_servis)->SUM('quantity_final');
$total = $sum_quantity_add + $quantity_actual;
What you are trying is treating array as numeric value and adding it, which is wrong, + operator behaves totally different while you are using with array, it merges the two array, it is different than array_merge too, so i recommend giving this answer a read + operator for array in PHP
UPDATED:
I still don't understand if you want to replace with the SUM from Servis_tareas in the Servis Table or sum the each others quantity and save it, Code below sum the data from both table and save it.
$id_servis = [1077, 1078];
$servisTareas = Servis_tareas::selectRaw("SUM(`quantity`) as total, `servis_id` ")
->where('servis_id', $id_servis)
->groupBy('servis_id')
->having('total', '>', 0)
->get();
$foundId = [];
$servisTotal = Servis::query()->whereIn('id', $id_servis)->pluck('quantity_final', 'id')->toArray();
foreach ($servisTareas as $servisTarea) {
$foundId[] = $servisTarea->servis_id;
$total = $servisTarea->total + ($servisTotal[$servisTarea->servis_id] ?? 0)
Servis::where('id', $servisTarea->servis_id)->update(['quantity' => $total]);
}
if (!empty($foundId)) {
Servis::whereNotIn('id', $foundId)->update(['quantity' => 0]);
}

What is my last row_number in mysql query?

I have a query like this:
$sql = "SELECT * FROM doctors WHERE city ='$city' LIMIT 10 ";
$result = $db->query($sql);
And I show the result like this :
while($row = $result->fetch_object()){
echo $row->city;
}
The Problem :
Mysql , will search through my database to find 10 rows which their city field is similar to $city.
so far it is OK;
But I want to know what is the exact row_number of the last result , which mysql selected and I echoed it ?
( I mean , consider with that query , Mysql selected 10 rows in my database
where row number are:
FIRST = 1
Second = 5
Third = 6
Forth = 7
Fifth = 40
Sixth = 41
Seventh = 42
Eitghth = 100
Ninth = 110
AND **last one = 111**
OK?
I want to know where is place of this "last one"????
)
MySQL databases do not have "row numbers". Rows in the database do not have an inherent order and thereby no "row number". If you select 10 rows from the database, then the last row's "number" is 10. If each row has a field with a primary id, then use that field as its "absolute row number".
You could let the loop run and track values. When the loop ends, you will have the last value. Like so:
while($row = $result->fetch_object()){
echo $row->city;
$last_city = $row->city;
}
/* use $last_city; */
To get the row number in the Original Table of the last resultant (here, tenth) row, you could save the data from the tenth row and then, do the following:
1. Read whole table
2. Loop through the records, checking them against the saved data
3. Break loop as soon as data found.
Like So:
while($row = $result->fetch_object()){
echo $row->city;
$last_row = $row;
}
Now, rerun the query without filters:
$sql = "SELECT * FROM doctors";
$result = $db->query($sql);
$rowNumber = 0;
while($row = $result->fetch_object()) {
if($row == $last_row) break;
$rowNumber++;
}
/* use $rowNumber */
Hope this helps.
What you can do is $last = $row->id; (or whatever field you want) inside your while loop - it will keep getting reassigned with the end result being that it contains the value of the last row.
You could do something like this:
$rowIndex = 0;
$rowCount = mysqli_num_rows($result);
You'd be starting a counter at zero and detecting the total number of records retrieved.
Then, as you step through the records, you could increment your counter.
while ( $row = $result->fetch_object() ) {
$rowIndex++;
[other code]
}
Inside the While Loop, you could check to see whether the rowIndex is equal to the rowCount, as in...
if ($rowIndex == $rowCount) {
[your code]
}
I know this is a year+ late, but I completely why Andy was asking his question. I frequently need to know this information. For instance, let's say you're using PHP to echo results in a nice HTML format. Obviously, you wouldn't need to know the record result index in the case of simply starting and ending a div, because you could start the div before the loop, and close it at the end. However, knowing where you are in the result set might affect some styling decisions (e.g., adding particular classes to the first and/or last rows).
I had one case in which I used a GROUP BY query and inserted each set of records into its own tabbed card. A user could click the tabs to display each set. I wanted to know when I was building the last tab, so that I could designate it as being selected (i.e., the one with the focus). The tab was already built by the time the loop ended, so I needed to know while inside of the loop (which was more efficient than using JavaScript to change the tab's properties after the fact).

Pull 5 entries from DB, modify entries, put those 5 entries into an array so I can find the average

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;

PHP: Counting entries in a loop and using them in a calculation

I have a loop in PHP as follows:
$getDetails = mssql_query ("SELECT * FROM BasketItems
WHERE BasketID = '".$_GET['id']."' ");
while ($detailsrow = mssql_fetch_array($getDetails)) {
$TotalSetPrice = $detailsrow['FinalPrice'] * $detailsrow['Qty'];
echo $TotalSetPrice;
$numberofent = count($detailsrow['FinalPrice']);
echo "######NUMBER#####: $numberofent";
$TotalPrice = ?????;
######VARIOUS DATA##############
}
So ok i'm not an expert at PHP by any means, thats the first thing. FinalPrice is the price of an item in the DB that someone has selected. However the customer can have any number of quantity of those items.
So FinalPrice * Qty = TotalSetPrice
However the customer may also have different sets of items within the basket.
So I need to calculate TotalSetPrice * (Number of sets of items Within the DB)
SO I googled, and came up with count(), but if I just count($detailsrow) it returns 56 entries, this is the number of overall pieces of data if that makes sense. I just want to count the dumber of actual data sets. I tried counting finalprice but that just returns 1, which isn't correct either.
Can anyone give me some guidence on how you are meant to count the number of entries in an array loop such as this. I hope that makes more sense than I feel it does.
SELECT FinalPrice, Qty,(FinalPrice * Qty) AS TotalSetPrice
Just use mysql, so that you no longer use with php which you will need to write a longer code
$TotalPrice += $TotalSetPrice;
This is short for: $TotalPrice = $TotalPrice + $TotalSetPrice;

php query does not retrieve any data?

well, i wanna pull out some data from a mysql view, but the wuery dos not seem to retrieve anything ( even though the view has data in it).
here is the code i've been "playing" with ( i'm using adodb for php)
$get_teachers=$db->Execute("select * from lecturer ");
//$array=array();
//fill array with teacher for each lesson
for($j=0;$j<$get_teachers->fetchrow();++$j){
/*$row2 = $get_lessons->fetchrow();
$row3=$row2[0];
$teach=array(array());
//array_push($teach, $row3);
$teach[$j]=mysql_fetch_array( $get_teachers, TYPE );
//echo $row3;*/
$row = $get_teachers->fetchrow();
//$name=$row[0]+" "+$row[0]+"/n";
//array_push($teach, $row1);
echo $row[0]; echo " ";echo $row[1]." ";
//$db->debug = true;
}
if i try something like "select name,surname from users", the query partially works . By partially i mean , while there are 2 users in the database, the loop only prints the last user.
the original query i wanted to execute was this
$get_teachers=$db->Execute("select surname,name from users,assigned_to,lessons
where users.UID=assigned_to.UID and lessons.LID=assigned_to.LID and
lessons.term='".$_GET['term']."'");
but because it didnt seem to do anything i tried with a view ( when you execute this in the phpmyadmin it works fine(by replacing the GET part with a number from 1 to 7 )
the tables in case you wonder are: users,assigned_to and lessons. ( assigned_to is a table connecting each user to a lesson he teaches by containing UID=userid and LID=lessonid ). What i wanted to do here is get the name+surname of the users who teach a lesson. Imagine a list tha displays each lesson+who teaches it based on the term that lesson is available.
Looking at http://adodb.sourceforge.net/ I can see an example on the first page on how to use the library:
$rs = $DB->Execute("select * from table where key=123");
while ($array = $rs->FetchRow()) {
print_r($array);
}
So, you should use:
while ($row = $get_teachers->fetchrow()) {
instead of:
for ($j = 0; $j < $get_teachers->fetchrow(); ++$j) {
The idea with FetchRow() is that it returns the next row in the sequence. It does not return the number of the last row, so you shouldn't use it as a condition in a for loop. You should call it every time you need the next row in the sequence, and, when there are no more rows, it will return false.
Also, take a look at the documentation for FetchRow().
for($j=0;$j<$get_teachers->fetchrow();++$j){
... a few lines later ...
$row = $get_teachers->fetchrow();
See how you call fetchrow() twice before actually printing anything? You remove two rows from the result set for every 1 you actually use.
while ($row = $get_teachers->fetchrow()) {
instead and don't call fetchrow() again within the loop.
Because you're fetching twice first in the loop
for($j=0;$j<$get_teachers->fetchrow();++$j){
... some code ...
// And here you fetch again
$row = $get_teachers->fetchrow();
You should use it like this
while ($row = $get_teachers->fetchrow()) {

Categories