I have the following table that is meant to show a win/loss record and to have rankings. I'm running into two issues with it though.
First issue is that my rank <td> is not progressing like I want it to. What I mean by that is for each record that is looped and output, I want it to be numbered for.
i.e.:
1
2
3, etc.
The second part I cannot figure out is I want the person with the highest win total to be ranked the highest. I also want losses to be configured into that. So if someone is 5-0, their rank will be higher than someone's that is 5-1.
Could someone point me in the right direction with these issues I am running into?
<h2>Division 1</h2>
<table>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Wins</th>
<th>Losses</th>
</tr>
<?php
try {
//Prepare
if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE `division`=1")) {
$stmt->execute();
$stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses);
//var_dump($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
$stmt->store_result();
while ($row = $stmt->fetch()) {
?>
<tr>
<td>1</td>
<td><?php echo $ranking_firstname; ?></td>
<td><?php echo $ranking_wins; ?></td>
<td><?php echo $ranking_losses; ?></td>
</table>
<?php
}
} else {
echo "<p>There aren't any players in division 1 yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}
?>
You need to use ORDER BY like this
Do this:
SELECT * FROM team_rankings WHERE `division`=1" ORDER BY Wins DESC, Losses
More: link
For your first question you </table> needs to be out of your php while loop. Also have a counter which you can increment and show the order.
$count = 0;
while ($row = $stmt->fetch()) {
?>
<tr>
<td><php echo $count; $count++; ?></td>
<td><?php echo $ranking_firstname; ?></td>
<td><?php echo $ranking_wins; ?></td>
<td><?php echo $ranking_losses; ?></td>
</tr>
<?php } ?>
</table>
Something better? Use foreach
The numbering issue can be resolved as such:
$i = 1;
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $ranking_firstname; ?></td>
<td><?php echo $ranking_wins; ?></td>
<td><?php echo $ranking_losses; ?></td>
</tr>
<?php
$i++;
}
This sets a variable $i to '1' (outside the loop), echos the variable as the number in your <td>, and increments the variable $i++ before the loop is closed.
Oh yeah, and don't close your <table> inside the loop. :)
Looks like you want to use the ORDER BY clause in your query. It can sort by a column directly or by some calculation. For example, you could do:
SELECT *
FROM team_rankings
WHERE division = 1
ORDER BY
(wins - losses) DESC,
wins DESC
This way 1-0 would be ranked higher than 6-6 but lower than 2-1. How appropriate this is is up to you to decide.
Related
I want to show some records with while loops and some without loops. But a while loop ignores the first record and show other records.
if (isset($_SESSION['patient_no'])) {
$patient_id = $_SESSION['patient_no'];
$sql = $db->prepare("select * from patient_record JOIN medicine_potency ON reference_no=:reference_id and patient_code=:reference_no");
if (!$sql) {
echo $sql->errorInfo();
} else {
$sql->bindParam('reference_id', $patient_id, PDO::PARAM_INT);
$sql->bindParam('reference_no', $patient_id, PDO::PARAM_INT);
$sql->execute();
$sql->bindColumn('code', $id);
$sql->bindColumn('reference_no', $reference_no);
$sql->bindColumn('patient_name', $patient_name);
$sql->bindColumn('father_name', $father_name);
if ($sql->columnCount() > 0) {
$sql->fetch(PDO::FETCH_ASSOC);
?>
<tr bgcolor=" #005A04"><td colspan="2" style="text-align: center; color:#CCFFBB">Personal Information</td></tr>
<tr>
<td>Reference No</td>
<td><?php echo $reference_no; ?></td>
</tr>
<tr>
<td>Patient Name</td>
<td><?php echo $patient_name; ?></td>
</tr><?php while ($sql->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $medicine; ?></td>
<td><?php echo $potency; ?></td>
</tr>
Simple solution: You could reverse the while-loop to a do-while loop, so the first iteration it will use your first fetch. that only works if you have a single fetch before the loop obviously.
But I'm not sure what the point is in your case you do the same fetch before the loop, so why are you even needing it?
Use the OFFSET syntax in your MYSQL statement:
$sql = $db->prepare("select * from patient_record JOIN medicine_potency ON reference_no=:reference_id and patient_code=:reference_no OFFSET 1");
This will skip the first result, and move on.
This question already has answers here:
MySQLi query returns only one row
(3 answers)
Closed 5 years ago.
So I had some mysql code that I've begun to rewrite into mysqli and have run into a problem with the query, and that is when I execute it, I only receive one set of results instead of the several that I know it should be. This is the new code I am using and was wondering whether anyone had any ideas on where I'm going wrong?
code:
<?php
if ($result = $link->query("SELECT SUM(step_count.steps) as total, leagues.league_id, leagues.league_name
FROM step_count INNER JOIN logins on step_count.unique_id = logins.unique_id INNER JOIN leagues ON leagues.unique_id = logins.unique_id GROUP BY leagues.league_id, leagues.league_name ORDER BY `total`
DESC LIMIT 100 ", MYSQLI_USE_RESULT))
$rank = 1; {
$row = $result->fetch_assoc();
$result->close();
}
?>
<tr>
<td>
<?php echo $rank++; ?>
</td>
<td>
<?php echo $row['league_name']; ?>
</td>
<td>
<?php echo $row['total']; ?>
</td>
</tr>
</table>
<?php
mysqli_close($link);
?>
you have to use a while loop
while($row = $result->fetch_assoc()){ ?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row['league_name']; ?></td>
<td><?php echo $row['total']; ?></td>
</tr>
<?php } ?>
try like this.
while($row = $result->fetch_assoc()){ ?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row->league_name; ?></td>
<td><?php echo $row->total; ?></td>
</tr>
<?php } ?>
you have to put a loop there.
you can replace this code and it will work
while($row =$result->fetch_assoc()){
?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row['league_name']; ?></td>
<td><?php echo $row['total']; ?></td>
</tr>
<?php }
$result->close();
}
?>
Fetch assoc retrieves one row as an associative array.
So you must use a while loop to keep fetching the rows until there are no more. The first example clearly illustrates how. I modified your whole code so you can copy paste everything. Do read the example though.
<?php
$query = "SELECT SUM(step_count.steps) as total,
leagues.league_id, leagues.league_name
FROM step_count
INNER JOIN logins on
step_count.unique_id=logins.unique_id
INNER JOIN leagues ON
leagues.unique_id=logins.unique_id
GROUP BY leagues.league_id, leagues.league_name
ORDER BY `total` DESC LIMIT 100";
$rank = 1;
if ($result = $link->query($query, MYSQLI_USE_RESULT)) {
while($row =$result->fetch_assoc()){
?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row['league_name']; ?></td>
<td><?php echo $row['total']; ?></td>
</tr>
<?php
}?>
</table>
<?php
}
mysqli_close($link);
Problems:
1) Just 3 id_penjualan rows were displayed in order history, it should be 4 id_penjualan rows.
2) jumlah and total have same value, it should be different for each other depending on sum of product quantity of each transaction.
Table tb_penjualan:
Table: tb_detail_penjualan:
Output:
Code:
<?php
$id_pelanggan=$_SESSION['user_session'];
$query="SELECT tb_penjualan.*, tb_pelanggan.nama_dpn, tb_pelanggan.nama_blk
FROM tb_penjualan LEFT JOIN tb_pelanggan
ON tb_penjualan.id_pelanggan=tb_pelanggan.id_pelanggan
WHERE tb_penjualan.id_pelanggan=:id_pelanggan
AND tb_penjualan.checkout='yes' ORDER BY id_penjualan";
$stmt=$con->prepare($query);
$stmt->execute(array(":id_pelanggan"=>$id_pelanggan));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$id_penjualan=$row['id_penjualan'];
if($stmt->rowCount()>0)
{
$query2="SELECT SUM(subtotal) AS total, SUM(jumlah) as total_jml
FROM tb_detail_penjualan
WHERE id_penjualan=:id_penjualan";
$stmt2=$con->prepare($query2);
$stmt2->execute(array(":id_penjualan"=>$id_penjualan));
$stmt2->execute();
$row2=$stmt2->fetch(PDO::FETCH_ASSOC);
$no=1;
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{?>
<tr>
<td></td>
<td><?php echo $no++;?></td>
<td> <?php echo $row['id_penjualan'] ;?></td>
<td><?php echo $row['nama_dpn'] ;?> <?php echo $row['nama_blk'] ;?> </td>
<td><?php echo date('d F y', strtotime($row['tanggal_blj'])); ?></td>
<td><?php echo $row2['total_jml']; ?></td>
<td> <?php $harga = $row2['total'] ?> <?php echo "Rp. " .number_format($harga, 0, ',', '.');?></td>
<td>Rp. </td>
<td></td>
</tr>
<?php
}
} else { ?>
<p>Order history empty</p>
<?php }?>
</tbody>
You have 2 queries in your code:
$query executed with $stmt
$query2 executed with $stmt2 and you fetch first row in $row2.
Then you have a loop, where you are fetching all rows from $stmt via variable $row. So $row contains each time values from next row of the first query.
But inside the loop you are also outputting information from $row2, which doesn't change (it is still the first row fetched before the loop), so each time it prints the same output.
there are multiple column in my table ..
col1 col2 col3 price
500 700 100 10
501 700 100 20
502 700 100 30
503 700 100 10
4 70
I need to get count of col1 and display its sum.
and also display sum of price column...
But the main thing is i need to display this in last row....after all data...how can select this and echo in last row...
plz help me...
I need to echo exactly as i put the data in above table...
I need sql query and also need help to echo only sum of this two column in last row only......
SELECT *,IFNULL(col1,'SUM'), count(*) as count FROM coupon_entry WHERE Group By col1 WITH ROLLUP
<?php if (is_array($data)) { foreach($data as $row){ ?>
<tr>
<td><?php echo htmlspecialchars($row['col1']); ?></td>
<td><?php echo htmlspecialchars($row['col2']); ?></td>
<td><?php echo htmlspecialchars($row['col3']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
</tr>
<?php } }?>
One solution is to calculate the sum in PHP with variables :
<?php if (is_array($data)) {
$totalCol1 = 0;
$totalPrice = 0;
foreach($data as $row){
$totalCol1 += $row['col1'];
$totalPrice += $row['price'];
?>
<tr>
<td><?php echo htmlspecialchars($row['col1']); ?></td>
<td><?php echo htmlspecialchars($row['col2']); ?></td>
<td><?php echo htmlspecialchars($row['col3']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
</tr>
<?php }
<tr>
<td><?php echo $totalCol1;?></td>
<td></td>
<td></td>
<td><?php echo $totalPrice;?></td>
</tr>
}?>
Either you have to do 2 separate queries or else you have to do your calculations in PHP - either one is fairly simple although the PHP solution will probably be slightly (negligibly?) faster.
double-query:
$r = query('SELECT *
FROM yada-yada');
while ($row = fetch($r)) {
echo "<td>$row[col1]</td>\n";
echo "<td>$row[col2]</td>\n";
echo "<td>$row[col3]</td>\n";
echo "<td>$row[price]</td>\n";
}
$r2 = query('SELECT COUNT(*) as cnt, sum(col1) as sum_col1,
sum(price) as sum_price
FROM yada-yada...');
if ($row = fetch($r2)) {
echo "<td>$row['cnt']</td><td>$row['sum_col1']</td>...$row['sum_price']...\n";
}
calculate in PHP:
$cnt = $sum_col1 = $sum_price = 0;
$r = query('SELECT *
FROM yada-yada');
while ($row = fetch($r)) {
echo "<td>$row[col1]</td>\n";
echo "<td>$row[col2]</td>\n";
echo "<td>$row[col3]</td>\n";
echo "<td>$row[price]</td>\n";
$cnt++;
$sum_col1 += $row['col1'];
$sum_price += $row['price'];
}
echo "<td>$cnt</td><td>$sum_col1</td>...$sum_price...\n";
Below is my sql query to get count and sum of column.
SELECT COUNT(coupon) As Total,SUM(Price) AS TotalPrice FROM coupon_entry
And put this in seprate row below table...
<?php
foreach($tot as $tota)
?>
<tr style="background-color:#33CCFF;">
<td colspan="2" style="text-align:right; font-weight:bold;">Total Coupon</td>
<td><?php echo $tota['Total'];?></td>
<td style="text-align:right; font-weight:bold;">Total Amount in Rs</td>
<td><?php echo $tota['TotalPrice'];?></td>
</tr>
<?php }?>
Let's say we have a query that gives a result from database's records. I want to put those records on a table, but not like row after row. I would like to make a table that will change row on every fifth cell. How can I do this using while or for?
Here is just an example of what I have made for now, but I can't make it change row on every fifth cell...
<table>
<tr>
<?php $count = 0; while ($count <= 5){ ?>
<td><?php echo $id[$count]->id; $usrname[$count]->usrname;</td>
<?php $count++;}?>
</tr>
</table>
Any idea???
Use a modulo operation:
if($count % 5 == 4) {
// end the current row, and start a new one
echo "</tr><tr>";
It divides $count by 5 and takes the remainder. So once in every 5 steps, it is 4 (at $count is 4, 9, 14, etc) and you can generate something different for every fifth record.
If you apply this on your code example, you get this:
<table>
<tr>
<?php
$count = 0;
while ($count <= 5) {
if($count % 5 == 4) {
// Generate a new row
echo "<\tr><tr>";
}
?><td><?php echo $id[$count]->id." ".$usrname[$count]->usrname;?></td><?php
$count++;
}
?>
</tr>
</table>
use array_chunk() before while or for
or set into loop:
if($count % 5 == 0) {
echo "</tr><tr>";
$count = 0;
}
Something like this could works. You can combine it with an inner for loop as well. But the working code highly depends to the Array that you're looping inside. So you might need to customise the following code to fit your set up.
Note that I eliminate the While loop, 'cause you didn't provide the actual array. you can place it before <tr> basically.
<table>
// you may start your while loop here
<tr>
<td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
<td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
<td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
<td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
<td><?php echo $id[$count]->id; $usrname[$count]->usrname; $count++; ?></td>
</tr>
</table>