retrieving values into an array - php

I'm trying to enter all the course_code that have a score < 40 into array and echo it out somewhere. The print_r($carry_over) returns nothing!
$carry_over = array();
while ($row8 = mysql_fetch_assoc($query8)) {
if ($row8['score'] < 40) {
$carry_over[] = array('m.course_code' =>$row8['course_code']);
}
}
print_r($carry_over);
$query8 = mysql_query("SELECT m.score , m.course_code FROM maintable AS m
INNER JOIN students AS s ON m.matric_no = s.matric_no
INNER JOIN courses AS c ON m.course_code = c.course_code
WHERE m.matric_no = '".$matric_no."'
AND m.level = '".$level."'
AND m.score < 40"
) or die (mysql_error());

Your $query8 variable (the database query) should be defined before the while() function. Right now, the while() function iterates over 0 rows which, of course, results in an empty array.
$carry_over = array();
while ($row8 = mysql_fetch_array($query8))
{
$carry_over[] = $row8['course_code'];
}
Since you already check for rows where the score is less than 40 in your SELECT query, the check inside the while() function is redundant. You also missed a single-quote in front of course_code (it was previously a dot), and finally; adding an array inside the $carry_over array is unnecessary when you can just add the value directly to the first array.
2nd UPDATE
$matric_no = MAKE_SURE_TO_DEFINE_THIS;
$level = MAKE_SURE_TO_DEFINE_THIS;
// Fetch rows
$query8 = mysql_query("SELECT maintable.score, maintable.course_code, maintable.matric_no, maintable.level, students.matric_no, courses.course_code FROM maintable, students, courses WHERE (maintable.matric_no = '" . $matric_no . "' AND maintable.matric_no = students.matric_no) AND (maintable.course_code = courses.course_code) AND (maintable.level = '" . $level . "')");
$carry_over = array();
while ($row8 = mysql_fetch_array($query8))
{
// Save data to array
$carry_over[] = $row8['course_code'];
}
echo 'We found ' . mysql_num_rows($query8) . ' rows';
print_r($carry_over); // DEBUG

The array loop should be
If($row8['score'] < 40)
$carry_over[] = $row8['course_code'];

I think you might have to debug $row8 array first. to see what is inside or it probably got nothing at all

Related

How to calculate the sum of number array elements from multiple database rows using php?

I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;
Replace your code with the following:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;

How to run a sql query inside a while of another sql query?

Hi my code as follow:-
$sql="SELECT student_id,DA1,DA2,DA3,DA4,DA5,DA6,HA1,HA2,HA3,HA4,HA5,HA6 from table";
$results = $result->query($sql);
while($row = $results->fetch_assoc())
{
$id = $row['student_id'];
$marks1 = $row['DA1'] + $row['HA1']/2 ;
$marks2 = $row['DA2'] + $row['HA2']/2 ;
$marks3 = $row['DA3'] + $row['HA3']/2 ;
$marks4 = $row['DA4'] + $row['HA4']/2 ;
$marks5 = $row['DA5'] + $row['HA5']/2 ;
$marks6 = $row['DA6'] + $row['HA6']/2 ;
$i = 1;
while($i <= 6)
{
$sql = "SELECT `grade`,`point` FROM `grades` where ${'marks' . $i} BETWEEN min and max";
$results = $result->query($sql);
$row = $results->fetch_assoc();
${'grade' . $i} = $row['grade'];
${'point' . $i} = $row['point'];
$i++;
}
$totalcredit = 20;
$sgpa= ($point1*$c1 + $point2*$c2 + $point3*$c3 + $point4*$c4 + $point5*$c5 + $point6*$c6) / $totalcredit ;
$sql = "UPDATE table SET `G1` = '$grade1', `G2` = '$grade2' ,`G3` ='$grade3',`G4` = '$grade4',`G5` = '$grade5',`G6` = '$grade6', `SGPA` = '$sgpa' WHERE student_id = '$id'";
$result->query($sql);
}
In this code i am trying to calculate grade and sgpa of a class. In the first query selecting all the details and calulating total marks in six subjects. In the second query i am storing the grade and point in variables with respect to the marks and then calculating the sgpa. Then the update query is performed to store the details in database.
The table consist of 100 rows. The code is working for the first row but does not work for another rows and returns empty values. I am recursively trying to calculate and update the table with data of all students. I would be highly grateful if anybody can help in running the code for all the rows.
Change the inner while loop like this:-
$i = 1;
while($i <= 6)
{
$sql = "SELECT `grade`,`point` FROM `grades` where ${'marks' . $i} BETWEEN min and max";
$results2 = $result->query($sql);
$row = $results2->fetch_assoc();
${'grade' . $i} = $row['grade'];
${'point' . $i} = $row['point'];
$i++;
}
In your code $results is getting overrided so changing it to $results2 in inner loop will solve your problem.

php while loop inside a foreach loop

Here this line $find_cond = str_replace('|',' ',$rem_exp); returns 225 and 245 number.
I want to get the records based on these two id number. But this below code returns the output repeatedly.
How do I properly put the while loop code inside a foreach?
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',' ',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id = '".$find_cond."' AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}
The problem is that you are redoing the sql query at every iteration of the loop, thus resetting the results internal pointer, so you keep fetching the same array.
$res = mysql_query($sql)
should be on it's own line before the while loop, and then
while($r = msql_fetch_array($res))
This will properly increment through the $res list.
Try this and you are done
As you were getting may get multiple id in the string after replacing it so its better to use IN the where clause
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',',',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id IN('".$find_cond."') AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}

Multiple Mysqli Select Statement, echo separated results

I have looked online for a solution to my problem for many hours to no avail.
I have multiple selct statements, receiving data from different mysql tables.
I want to echo completely separated results. Currently, results are printed as if they are one,
so I cannot work on the answers separately.
Suppose the output from table is:
100
200
300
400
I want to echo out:
result1 = 100;
result2 = 200;
etc
So I can work on the final results in another program. If a result is null, it should not produce an error,
but just post 0.
Example, if output from mysql table is:
100
null
null
100
I want the output to clearly show
result1 = 100;
result2 = 0;
result3 = 0;
result4 = 100;
etc.
$check_sco = 100;
$sql = "SELECT TABLE_1 FROM RIDER_1 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_2 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_3 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_4 WHERE score1=$check_sco";
if (mysqli_multi_query($con,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);//how to echo separated result that can be manipulated indepedently?
}
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
Thank you.
Why not just run them in sequence?
$check_sco = 100;
$riders = array();
for($i=1; $i<=4; $i++) {
$sql = "SELECT TABLE_1 FROM RIDER_" . $i . " WHERE score1=" . $check_sco;
$result = mysqli_query($con, $sql);
$row = $result->fetch_assoc();
$riders[] = ($row['TABLE_1']) ? $row['TABLE_1'] : 0;
}
Then you'll have an array with the results you want
You need to use IFNULL which if TABLE_1 is not null it will return TABLE_1 otherwise it will give you 0
SELECT IFNULL(TABLE_1, 0) FROM RIDER_1 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_2 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_3 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_4 WHERE score1=$check_sco

Fetching the result array from mysql query in php, while loop issue

I have this table in MySql db:
After running this query:
SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC
The result table look like this:
Now in php I try to fetch the result and iterate through the array to determine which group each coach belongs to and get his place in the ranking. Therefore I wrote this:
$groupsOfScoresQuery = "SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC";
$result = mysqli_query($dbc, $groupsOfScoresQuery);
if ($result) { // query did successfully run
$response['topCoaches'] = array();
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score["scores"] = $rowScore["score"];
$score["count"] = $rowScore["count(*)"];
$numberOfCoaches = $score["count"];
$scoresGroup = $score["scores"];
$response["scoresGroup"] = $scoresGroup; // HERE IS THE PROBLEM
.
.
.
more processing
} // end WHILE
Why $response["scoresGroup"] will always conatins the last value from the result? In this case this is 123. I thought that this is the first iteration through the loop and $response["scoresGroup"] wll hold first element (474), during the second iteration should hold 382 ? What I'm doing wrong here? Do I use correct function to fetch result? or should I use different loop to acheive my goal? Thanks for the help in advance.
You did not post the expected structure of $response; here is what I think you are trying to do:
while ($rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["scoresGroup"][] = array(
"scores" => $rowScore["score"],
"count" => $rowScore["count(*)"]
);
}
// $response["scoresGroup"][0]["scores"] = 474
// $response["scoresGroup"][0]["count"] = 1
// $response["scoresGroup"][1]["scores"] = 382
// $response["scoresGroup"][1]["count"] = 1
// $response["scoresGroup"][2]["scores"] = 123
// $response["scoresGroup"][2]["count"] = 1
Or perhaps:
while ($rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["scoresGroup"][$rowScore["score"]] = $rowScore["count(*)"]
}
// $response["scoresGroup"][474] = 1
// $response["scoresGroup"][382] = 1
// $response["scoresGroup"][123] = 1
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score[]["scores"] = $rowScore["score"];
$score[]["count"] = $rowScore["count(*)"];
$numberOfCoaches[] = $score["count"];
$scoresGroup[] = $score["scores"];
$response[]["scoresGroup"] = $scoresGroup; // HERE IS THE PROBLEM
Looking at the description of your question, you need to define a multidimensional array for storing all the results from query resultset.
Please refer the below code snippet
$groupsOfScoresQuery = "SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC";
$result = mysqli_query($dbc, $groupsOfScoresQuery);
if ($result) { // query did successfully run
$response['topCoaches'] = array();
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score["scores"] = $rowScore["score"];
$score["count"] = $rowScore["count(*)"];
$numberOfCoaches = $score["count"];
$scoresGroup = $score["scores"];
$response["scoresGroup"][] = $scoresGroup; //Notice the array here
.
.
.
more processing
} // end WHILE
You are settings $response['scoresGroup'] each time you run the loop, so at the end, it will contain only the last element. Try changing the variable you put the data into on each loop.
$x++;
$response['scoresGroup' . x] = $scoresGroup;

Categories