Getting total from mysql query with array - php

I have this code and i would like to get total combination of all categories
my code so far
for ($k = 0; $k < 4; $k++) {
$result= $DB->query("SELECT total FROM ".$DB->prefix("mystat")." WHERE year='$year' AND category='$categoryname[$k]'");
$row = $DB->fetchArray($result);
$total=$row['total'];
echo $total++;
}
let say i have this data
A - 1
B - 2
C - 3
my current output
123
my desired output
6
How do i correct this ?

It is because you are doing echo in loop. And also you logic is wrong. change your code like:
$total = 0;
for ($k = 0; $k < 4; $k++) {
$result= $DB->query("SELECT total FROM ".$DB->prefix("mystat")." WHERE year='$year' AND category='$categoryname[$k]'");
$row = $DB->fetchArray($result);
$total +=$row['total'];
}
echo $total; // DO echo here
Also if you don't need categories and total separately and only need sum of all then its better to use SUM with group by category in sql.

Related

how to divide students in sql

I want to divide student group-wise and store them in database
students 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15.....20
Example: Total no.of students 20
Make 4 students per group (1,2,3,4 group1 and 5,6,7,8 group2 etc.....)
Then there should 5 groups created
i tried like this where the mistake i am doing in for loops.
$studentQuery = $conn->query("
select s.student_pid,i.email,s.student_email,s.student_fname,
s.student_lname,s.profile_pic from r_job_invitations i
LEFT JOIN
tbl_students s
ON
i.email = s.student_email
where i.id_job = ".$jobID." and inv_res = 1");
$totalIndividuals = mysqli_num_rows($studentQuery);
$groups = round($totalIndividuals/5,0,PHP_ROUND_HALF_DOWN);
for ($j = 1; $j <= $groups; $j++) {
for ($i = 0; $i <= $totalIndividuals; $i++) {
$GroupsQuery = $conn->query("INSERT INTO
r_test_group (student_id,job_id,group_name)
values ('".$studentResults['student_pid']."',
'".$jobID."','Group'".$j." )");
}
}
$stuData = array();
while($studentResults = $studentQuery->fetch_array()) {
$stuData[] = $studentResults;
}
$totalIndividuals = mysqli_num_rows($studentQuery);
$groups = round($totalIndividuals/$gd_individuals,0,PHP_ROUND_HALF_DOWN);
$count=0;
for($j = 0; $j<$groups; $j++) {
for($i =0; $i< $gd_individuals; $i++) {
if($stuData[$count]['student_pid']) {
echo "INSERT INTO r_test_group (student_id,job_id,group_name) values (".$stuData[$count]['student_pid'].", ".$jobID.",Group".$j." )";
$count++;
}
}
}
exit;
first forloop is to divide groups.
Second forloop is to divide for students.
You could use flooring to translate a student id to a group id:
INSERT INTO r_test_group
(student_id,job_id,group_name)
SELECT student_pid, id_job, CONCAT('group', FLOOR((student_id - 1) / 4) + 1))
FROM tbl_students s
JOIN r_job_invitations j ON j.email = s.student_email
Considering there is no gaps between the records
select Concat('group',(your_col - 1 ) / 4 + 1 )
From yourtable
Note : This will not work when there is gaps. If you have gaps then you need to generate row number for each row then replace then student_id with row number in my query.
I think your code giving you more student then you are looking for. in your code in first loop its running for number of groups time then for each group in next for loop its running for all students in each group.
$limit = (int)($totalIndividuals/$groups);
for($j =0; $j<$groups;)
{
for($i =0; $i<$totalIndividuals; $i++)
{
if($i % $limit == 0)
$j++;
$GroupsQuery = $conn->query("INSERT INTO r_test_group (student_id,job_id,group_name) values ('".$studentResults['student_pid']."', '".$jobID."','Group'".$j." )");
}
}

can't get the logic to restart looping

I have 15 databases 1,2,3,4, ... 15
and I have the variable $i default at 1 and each time the $i count gets to 3, $i restarts the looping from 1 again until 3 and it will stop until value from database is done counting.
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
while($detail = mysql_fetch_array($detailPsycho)){
for($i = 1;$i<=3;$i++){
echo $detail['sequence']."&".$i." <br>";
}
}
and run over like this :/
1&1
1&2
1&3
2&1
2&2
2&3
You try to do a loop (for{}) in a loop (while{}) which is a complicated way of doing something trivial. This is the "while+for" result :
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
i = (int) 1;
while($detail = mysql_fetch_array($detailPsycho)) {
echo $detail['sequence']."&".$i." <br>";
$i++;
if ($i > 3) $i = 1;
}

Loop through results from mysql, and sum values

I use a while loop to process table record like this:
$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
while ($show_s = mysqli_fetch_assoc($result)) {
$quantity = $show_s['sells_quantity'];
}
mysqli_free_result($result);
}
I have all my table records, and now I want to sum up all quantity fields , but I don't know how to do it.
For example, if I got 10 records quantity for records like 2, 1, 5, 1, 3, 6 etc, I would like to sum them like this: 2+1+5+1+3+6 = 18
If you can do something in mysql - do it. Use SUM aggregation function:
$get_s = "SELECT SUM(sells_quantity) as sells_sum FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
$show_s = mysqli_fetch_assoc($result);
echo $show_s['sells_sum'];
}
mysqli_free_result($result);
Still, if you need certain values of rows - you can count sum in a loop:
$get_s = "SELECT * FROM sells ORDER BY sells_date";
if ($result = mysqli_query($AECONNECT, $get_s)) {
$total = 0;
while ($show_s = mysqli_fetch_assoc($result)) {
$quantity = $show_s['sells_quantity'];
$total += $quantity;
}
mysqli_free_result($result);
echo $total;
}
But mysql SUM() is preferrable.

How do I fix this php to include full list from array?

$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids = $array[$i].',';
$q2 = mysql_query("SELECT * FROM item WHERE approved = 1 AND id IN(".$userids."0)");
echo $userids;
//NOTE: my echo is spitting out "18622,44968,44968," but when using $userids in mysql query it doesn't include the full list of numbers
}
}
I put }'s after mysql query to try to include variable in the for loop, if i close brackets before query $userids only prints last number from array.
Close the parenthesis before your query and use concatenation instead of re-assigning $userids on each iteration:
$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids .= $array[$i].',';
// ^ missing the period here
}
}
$q2 = mysql_query("SELECT * FROM item LEFT JOIN subcategory
ON item.subcategory_id=subcategory.subcategory_id LEFT JOIN genre ON item.genre_id=genre.genre_id WHERE approved = 1 AND broken = 0 AND id IN(".$userids."0)");
echo $userids;
You could also just get rid of the for-loop and use implode():
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
$userids .= implode(',', $array) + ',';
}
While this may fix the issue, know that this isn't very efficient nor maintainable. It would make more sense to use SQL JOIN syntax to combine a user's recent views with the sub-categories all in one query.

PHP array for loop

I want to show the array value $result[] from the for loop calculation. However, it shows me nothing on the page. Is there is anything wrong in the below code?
$sql= "SELECT * FROM items where itemID =3 ";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_array($result1)){
$quantity[] = $row ['quantity'];
$month[] = $row ['month'];
}
$alpha = 0.3;
for($i = 1; $i > 12; $i++){
$result[$i] = ($quantity[$i] - $result[$i-1]) * $alpha + $result[$i-1];
}
foreach ($result as $key => $value ){
echo "$value";
}
Your for loop has an error. You have
for($i = 1; $i > 12; $i++)
but it should be
for($i = 1; $i < 12; $i++)
This is not directly the answer to your question, but there are few things that hasn't been mentioned that concern the way you query and process your data:
Your SELECT statement doesn't have specific order specified. Since order of records is not preserved you can get records out of correct order and get invalid calculations. Use ORDER BY (e.g. ORDER BY month) or make use of month values and extract exactly previous month's value from array(s) (if it is what you're doing in your code).
Your current code relies on the fact that the resultset from DB will contain (at least) 12 records. If for some reason it will produce less records your for loop will brake.
It's uncertain from the information in the question but it looks like you might need a year in your query unless the table contains records only for one year.
Now, you can calculate the whole thing on DB side with a query like this
SELECT i.month,
COALESCE((i.quantity - p.quantity) * 0.3 + p.quantity, 0) value
FROM items i LEFT JOIN items p
ON i.itemID = p.itemID
AND i.`year` = p.`year`
AND i.month = p.month + 1
WHERE i.itemID = 3
AND i.`year` = 2013
ORDER BY month
SQLFiddle
That's assuming (and I'm not sure about that) you actually need to read previous month's quantity values for your calculations and month column is of integer type
There is an obvious flaw in the logic. You try to get the $i index form $quantity. However, you can't be sure $quantity will have this index.
Supposing that itemId is not the primary key, I would do something like this:
$sql = "SELECT * FROM `items` WHERE `itemID` = 3";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_assoc($result1)){
$quantity[] = $row ['quantity'];
}
$alpha = 0.3;
$i = 1
foreach ($quantity as $elem) {
if ($i >= 12)
break;
$result[$i] = ($elem - $result[$i-1]) * $alpha + $result[$i-1];
$i++
}
foreach ($result as $value ){
echo $value;
}

Categories