php mysqli query select - php

I have 3 different tables
table 1 keep general scores over the year
table 2 and 3 is event specific
only common field in all 3 is a member ID
I need to select 5 top score results for each member from table1 combine them with 1 specific result from table 2 and 3
I managed to get everything together in a temp table, but cnt get the output the way I need it
example what i have and need.
Original code
$prevQuery = "SELECT distinct member_id FROM scores";
$prevResult = $conn->query($prevQuery);
while($row = $prevResult->fetch_assoc()) {
$scores=("SELECT member_id,event_id,event_date,event_score FROM scores where member_id = ".$id." ORDER BY event_score DESC LIMIT 5");

Query:
select * from temp_table order by mem_id asc
PHP:
you can simple do your expected result in your application like this
<?php
$result = array(array('mem_id'=>1,'location'=>'A','date'=>'20/05/2017','score'=>100),array('mem_id'=>1,'location'=>'B','date'=>'21/05/2017','score'=>103),array('mem_id'=>1,'location'=>'C','date'=>'22/05/2017','score'=>106),array('mem_id'=>1,'location'=>'C','date'=>'23/05/2017','score'=>108),
array('mem_id'=>2,'location'=>'A','date'=>'20/05/2017','score'=>105),array('mem_id'=>2,'location'=>'B','date'=>'21/05/2017','score'=>109),array('mem_id'=>2,'location'=>'C','date'=>'22/05/2017','score'=>111),array('mem_id'=>2,'location'=>'C','date'=>'23/05/2017','score'=>110));
$new_result=array();
foreach($result as $key=>$row)
{
$new_result[$row['mem_id']][]=$row;
}
echo "<table border='1px'>";
echo "<thead><tr><th>S.No</th><th>date</th><th>score1</th><th>date</th><th>score2</th><th>date</th><th>score3</th><th>date</th><th>score4</th></tr>";
echo "<tbody>";
foreach($new_result as $key=>$row)
{
echo "<tr><td>".$key."</td>";
foreach($row as $key1=>$row1)
{
echo "<td>".$row1['date']."</td>";
echo "<td>".$row1['score']."</td>";
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
OUTPUT :
S.No date score1 date score2 date score3 date score4
1 20/05/2017 100 21/05/2017 103 22/05/2017 106 23/05/2017 108
2 20/05/2017 105 21/05/2017 109 22/05/2017 111 23/05/2017 110

Related

Calculate the Student Rank

I have followed the previous question and answer through this link:
Fetch the row of next in rank to the “rank of last id”?
Sadly, I couldn't get the result as I expected.
The expected result:
id score rank
1 78 4
2 80 3
3 100 1
4 88 2
5 56 5
In database, I have the id, score in my table: result.
Now, what I am trying is too put the rank in the table.
My code is as below:
<?php
include ('config.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>ranking</title>
</head>
<body>
<?php
if($db){
//Create Query
$sql = "SELECT * FROM result ORDER BY score DESC";
//Execute Query
$result = mysqli_query($db,$sql);
if($result -> num_rows > 0){
//output data for each row
echo "
<br><br>
<table align='center'; border=1; style='text-align:center'>
<tr>
<td colspan='4'>RANKING TABLE</td>
</tr>
<tr>
<th>Bil</th>
<th>ID</th>
<th>Result</th>
<th>Rank</th>
</tr>
";
$i = 0;
//Store rows by rank + get the last_id_rank from the first row
$by_ranks = array();
$last_id_rank = FALSE;
//Display Result
while($row = $result -> fetch_assoc()){
$i++;
echo "
<tr>
<td>".$i."</td>
<td>".$row["id"]."</td>
<td>".$row["score"]."</td>
<td>".$row["rank"]."</td>
</tr>
";
$by_ranks[$row["rank"]][]=$row;
if($last_id_rank === FALSE){
$last_id_rank = $row["rank"];
}
}
//Get the result
$get_results = function($by_ranks, $last_id_rank){
//Get sorted array that's smaller $last_id_rank
$ranks = array_filter(array_keys($by_ranks),function($var) use ($last_id_rank){
return $var < $last_id_rank;
});
rsort($ranks); //Sort ranks by DESC
//Get rank that is just smaller than $last_id_rank
if(sizeof($ranks) == 0){
return array();
}
else{
return $by_ranks[$ranks [0]];
}
};
$results = $get_results($by_ranks,$last_id_rank);
//Display results
foreach($results as $row){
echo "
<br><br><br><br>
<tr>
<td>{$row["id"]}</td>
<td>{$row["score"]}</td>
<td>{$row["rank"]}</td>
</tr>
";
}
echo "
</table>
";
}
}
else{
echo "Failed to connect";
mysqli_close($db);
}
?>
</body>
</html>
The data in my database is as below:
id score rank
1 78 0
2 80 0
3 100 0
4 88 0
5 56 0
Given your table structure, you could update the table to have rank values with the following:
UPDATE result
LEFT JOIN result AS sub
ON sub.score > result.score
SET rank = COUNT(sub.id) + 1
The left join does the comparison with other rows in the table and setting the rank to the count with a higher score plus one gives you ranks starting at 1 instead of 0. Also, if you want ties to get the lowest rank that any of them would have, just change sub.score > result.score to use >=
Once you have your data in place, you can just access the rank values in php from the result of your SQL query and don't need to do calculations on the fly.
To create the result required from a table containing only id and score you could do the following.
select * from(
select id,score,(#rank:=#rank+1) as rank
from tbl
cross join
( select #rank:=0 ) T1
order by score desc
) T2
order by id
;
which results in
id score rank
1 78 4
2 80 3
3 100 1
4 88 2
5 56 5

Selecting a value by row number

I have the following MySQL table:
table_1
id | value_1 | value_2 | value_3
1 hehe haha stack
2 over flow me
3 123 abc hello
4 hi random php
5 html js css
How can I select value_2 from 3rd row, which is "abc"?
Something like $rows[3]['value_2']
Here's the code I had tried with:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
$rows=mysql_fetch_array($sql);
//And then I tried accessing it by "$rows[3]['value_2']" and $rows['value_2'][3]
I can't use SELECT * FROM table_1 WHERE id='3', because I need to access multiple lines (all of them). I can't use a WHILE loop also, because I need the values in very different places in the code.
mysql_fetch_array only returns a row corresponding to the query. The proper use of mysql_fetch_array is as such:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
while ($row = mysql_fetch_array($sql)) {
printf("ID: %s value_2: %s", $row[0], $row[2]);
}
http://www.php.net/manual/en/function.mysql-fetch-array.php
Found the answer. You can now access them how you wanted.
$sql=mysql_query("SELECT * FROM settings ORDER BY `settings`.`id` ASC");
$id=0;
while ($rows = mysql_fetch_array($sql)) {
$settings[$id]['value_1']=$rows['value_1'];
$settings[$id]['value_2']=$rows['value_2'];
$settings[$id]['value_3']=$rows['value_3'];
$id++;
}
echo $settings[5]['value_3'];
echo $settings[5]['value_1'];
echo $settings[4]['value_2'];
echo $settings[0]['value_3'];

Do not display duplicate result

Here is my table register:
id name student_id date presence absence_note Tusername
50 hassimkhan 1112815 2014-03-08 P saahir
56 Karishma kods 1119112 2014-03-08 P saahir
58 Karishma kods 1119112 2014-03-09 P saahir
60 hassimkhan 1112815 2014-03-09 A saahir
Here is my loop to display the result:
$retrieve = mysql_query("SELECT DISTINCT(student_id),presence FROM register");
while($row = mysql_fetch_array($retrieve))
{
echo $row['student_id'];
}
I know for e.g id 56 and 58 with student_id: 1112815 record are different in a way, but i want to display it only one time e.g of result of these data:
1112815
1119112
Any help?
Try GROUPing instead:
SELECT student_id, presence FROM register GROUP BY student_id
(untested)
retrieve = mysql_query("SELECT student_id,presence FROM register GROUP BY student_id");
while($row = mysql_fetch_array($retrieve))
{
echo $row['student_id'];
}

Student Position ranking in mysql

I have a project on student ranking. The sample school does three terminal exam in a year. I created three different tables for each terminal exam, (i.e. firstermsar for first, secondtermsar for second, thirdtermsar for third term respectively).
Table structure is like this:
id studentid matca1 matca2 matexam engca1 engca2 engexam
1 2 15 14 40 12 10 60
2 1 10 5 56 9 13 35
3 4 11 9 45 14 17 40
4 5 14 1 50 20 0 60
Students with id 4 and 5 are in class1 while students 2 and 1 are in in class2. I have a seperate table for classes and also seperate table for student profile info.
Now, I already output the result slip but without ranks which looks like this
StudentId: 2 Full Name: Fawaz James Class: Pry 2 Overall Position: -
1stAss 2ndAss ExamScore Grade Position Rmks
Mark Obtainable 20 20 60
English 12 10 60 A - Excellent
Mathematics 15 14 40 B - V. Good
Though am a starter, and my code is a mess, its provided underneath. Moreover I need help with calculating the overall position on class basis and subject position on class basis. Please help me as my project depends on this for approval and am in my deadline week before I got introduced to stack Overflow.
$query = "SELECT * FROM firsttermsars
WHERE studentID=$stuID AND year=\"$_SESSION[year]\""; #27
$result = mysql_query($query)
or die ("Couldn't execute query.");
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
echo "<h2> First Term Stint Report Sheet for $namet during the SESSION $year</h2>";
echo "<table class='table1'>";
echo "<tr>";
echo "<td></td>";
echo "<td><b>1st Assessment</b></td><td><b>2nd Assessment</b></td>
<td><b>Mid Term<br />Exam</b></td><td><b>Mid Term<br />Total Score</b></td><td><b>Grade<br />Point</b></td></tr>";
echo "<tr> <td><b>Mark Obtainable</b></td><td><b>30</b></td><td><b>20</b></td><td><b>50</b></td><td><b>100</b></td><td><b>||=||</b></td></tr><tr>";
$tetal = $row['thirdengtest']+$row['thirdengexam']+$row['eng1'];
if ($tetal >="1") {
$q2 = "1";
$sq2 = "100";
echo "<td>English Language: </td>";
echo "<td>{$row['eng1']}</td><td>{$row['thirdengtest']}</td><td>{$row['thirdengexam']}</td> <td>";
$total1 = $row['thirdengtest']+$row['thirdengexam']+$row['eng1'];
echo $total1."</td><td>";
if ($total1>="75")
echo "A1";
elseif ($total1>="70")
echo "B2";
elseif ($total1>="65")
echo "B3";
elseif ($total1>="60")
echo "C4";
elseif ($total1>="55")
echo "C5";
elseif ($total1>="50")
echo "C6";
elseif ($total1>="45")
echo "D7";
elseif ($total1>="40")
echo "E8";
elseif ($total1>="1")
echo "F9";
elseif ($total1=="0")
echo "-";
else
echo "F";
echo "</td></tr>";
}
$tetal = $row['thirdmathtest']+$row['thirdmathexam']+$row['math1'];
if ($tetal >="1") {
$q3 = "1";
$sq3 = "100";
echo "<tr>";
echo "<td>Mathematics </td>";
echo "<td>{$row['math1']}</td><td>{$row['thirdmathtest']}</td> <td>{$row['thirdmathexam']}</td> <td>";
$total2 = $row['thirdmathtest']+$row['thirdmathexam']+$row['math1'];
echo $total2."</td><td>";
if ($total2>="75") echo "A1"; elseif ($total2>="70") echo "B2"; elseif ($total2>="65") echo "B3"; elseif ($total2>="60") echo "C4"; elseif ($total2>="55") echo "C5"; elseif ($total2>="50") echo "C6"; elseif ($total2>="45") echo "D7"; elseif ($total2>="40") echo "E8"; elseif ($total2>="1") echo "F9"; elseif ($total2=="0") echo "-"; else echo "F";
echo "</td></tr>";
}
?>
I hope you can help me like this, and hope is not complicated. I wanted to add the picture of the output but its complaining i don't have the required reputation
Firstly, in the database, make a new column for total('Total') and ('Grade'), and when you are submitting the marks details to your database, add the marks and grade and then submit the total to the database, instead of calculating them while retrieving the information.
Second, when you are selecting students from the database, use the SQL command:
SELECT * FROM firsttermsars ORDER BY Total DESC
More info on ORDER BY
This will automatically return the list of students in descending order of their total marks.
Similarly, for subject ranking, you can have a separate table, where ranking is done on subject marks
Then, while retrieving the data,
<table>
<?php
while ($i<$num) //num is number of rows
{
?>
<tr><td><?php echo mysql_result($result,$i,"Name"); ?></td>
//... Similarly for all clumns
<?php
}
?>
</table>
This should make the table with all students ranked according to their total marks. Similarly you can make a table for ranking by subject marks.
This is how i would solve the problem. Hope I helped!
Although i am late, but it may help some one.
First of All you should calculate Obtained marks and store in database table.
For simplicity i am showing just 3 column.
Id Name Obtained
1 A 100
2 B 58
3 L 88
4 F 102
5 C 99
Insert the row in table , then run this query to get Position of student.
SELECT id, name, Obtained, FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC )
FROM scores )
) AS position
FROM scores
WHERE id = 5
Detail here https://dba.stackexchange.com/questions/13703/get-the-rank-of-a-user-in-a-score-table

Select where two rows have the same column value and echo them

In the table "ogitems", I have a column called "itemname", "month", and "price".
There duplicate items, arranged by month.
I want to check "itemname" to see if any rows have the same value for itemname, and if yes, echo the "itemname" along with the last two months and the pricing for these two months.
EXAMPLE:
"itemname" = CHEESE CHEDDAR
CHEESE CHEDDAR is found in months 11 AND 12 (so there is two records/rows for CHEESE CHEDDAR). 11 has "price" of 51 while 12 has "price" of 54
I want to echo that information into an anchor tag...
<a href="pricetrend.php?date=<?php echo "" . $row['month'] . "" ?>&price1=<?php echo $price1; ?>&price2=<?php echo $price2; ?>&item=<?php echo "" . $row['itemname'] . ""?>;">
Basically, I am trying to grab the two most recent prices for one item and echo them into this anchor tag. Thanks in advance for any help!
I am assuming that your month is a date field, this should work
SQL Fiddle link: http://sqlfiddle.com/#!2/d63a0/4
SELECT * FROM (
SELECT
o.itemname,
o.month,
( SELECT price FROM ogitems i WHERE i.itemname = o.itemname AND i.month<o.month ORDER BY MONTH DESC LIMIT 1) AS last_month_price,
o.price AS current_month_price
FROM
ogitems o
ORDER BY
o.month DESC
) AS items
GROUP BY
items.itemname
HAVING
items.last_month_price IS NOT NULL
select * from ogitems where itemname='CHEESE CHEDDAR' order by month desc limit 2
This sql statement should fix your problem
<?php
$result = mysql_query("select * from ogitems where itemname='CHEESE CHEDDAR' order by month desc limit 2")
while ($row = mysql_fetch_assoc($result)) {
echo $row["itemname"];
echo $row["month"];
echo $row["price"];
}
?>

Categories