Image to the first row - php

Running a mysql query that returns users with their daily highscores.
This is the php file that displays the highscore:
<table border="0" width="100%"><?php echo highscore()?>
</table>
This is the php that handles the mysql query (highscore function):
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td>';
echo '</tr>';
The mysql query that I have results in the user with the highest score getting on top of the table that you see above.
Now I would like to add a crown to the user that has the most points.
The question is how to add an image(crown.png) to the first row which is the user with the highest score.
Thanks in advance.

I assume you order users by score DESC.
$set = 0;
while() {
echo '<tr';
echo '<td>';
if(!$set) {
echo '<img src="crown.png" alt="crown" />';
}
// ... the rest of the code
$set = 1;
}

if (empty($notfirst)){
echo "crown";
$notfirst=1;
}

i only see a quick and dirty solution, given the code you provide.
I guess you call this code in a loop?
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td>';
echo '</tr>';
so just declare a variable before you start the loop:
$first = true;
then inside your loop, change your code to:
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td><td>'.$first?'<img src=\"crown.png\" />':''.'</td>';
echo '</tr>';
$first = false;

If you wanted to do this sans PHP you could make your table and use CSS3's new :first-child pseudo-selector to add the crown as a background image to the first row.
table tr:first-child { background: url("crown.gif") no-repeat; }

Related

How to restrict number of cells per row in a html table from database with PHP

I am in the process of attempting to set up an e-commerce store for my website. I plan on having it split into three categories (this part is already working), and then listing items from a MySQL database to a table.
I already am familiar with how to use the MySQL LIMIT function to limit results, but I want it to list all items from the database that match the category to the table and restrict it to a maximum of three items per row.
i.e.
Table
Item1 Item2 Item3
Item4 Item5 Item6
Item7 etc. etc.
Due to how few items I am listing per category, pagination is not necessary.
How would I even begin to attempt to set this up properly with a while loop? I saw something about a slice function with PHP, but not sure if that would fit my needs.
I have the base while loop working as intended, I just am not sure where to begin to break the loop apart into different rows in the table. I did a google search, and most I found was something related to slicing, but it wasn't related to MySQL fetch array functions.
$sql = $db->query('SELECT * FROM store_items WHERE store_cat = "Apparel"');
if(is_object($sql) && $sql->num_rows > 0)
{
while($row = $result->fetch_array())
{
echo '<tr>';
echo '<td height="250">';
echo '<img src="" alt="" height="180" /><br />'.$row['store_name'];
echo '<br /><br />\$'.$row['store_price'].'<br />'.$row['store_desc'];
echo '<br /><href="">Add to Cart</a>';
echo '</td>';
echo '</tr>';
}
}
I wish to have the while loop output the data from the database in rows of 3 items each. Right now, it only outputs the data in 1 row, unless I run a different query for each row (and just as many while loops).
As, you want to display item with images. Try CSS Grid to display it. That way you will have more control over its layout regarding different screen sizes.
Here I am using, bootstrap grids, you can use different if you want.
$sql = $db->query('SELECT * FROM store_items WHERE store_cat = "Apparel"');
if(is_object($sql) && $sql->num_rows > 0)
{
echo '<div class="row">'; //Bootstrap Row
while($row = $result->fetch_array())
{
echo "<div class= 'col-md-4'>"; //Bootstrap Column
echo '<img src="" alt="" height="180" /><br />'.$row['store_name'];
echo '<br /><br />\$'.$row['store_price'].'<br />'.$row['store_desc'];
echo '<br /><href="">Add to Cart</a>';
echo '</div>';
}
echo '</div>';
}
In the code above, we are dividing the available width in three equal parts.
It's just styling issue your code is fine. If you just want to achieve this, avoid unnecessary codes or logics that will only slow down performance. This way you will have more option, you can style images and tags below it. There is other bootstrap classes for image thumbnails.
$row = fetch();
while($row) {
echo '<tr>';
for($i = 0; $i < 3; ++$i) {
echo '<td>';
if ($row) {
//print the card here
//then fetch next row
$row = fetch();
} else {
//nothing needs be done here, since you are just generating empty td tags
//to keep the table aligned - same number of columns in all rows.
//but you can place here something too.
}
echo '</td>';
}
echo '</tr>';
}
I highly recommend css grid for this. That way you would specify the number of items per row in your css & you wouldn't have to worry about appropriately placing the tr tag. I literally have to search for css grid every time i need to use it, and I'm on mobile so i don't have an example.
But with your current setup, you could do:
$count=0;
echo '<tr>';
while(...){
$count++;
//your other code
if ($count%3===0)echo '</tr><tr>';
}
echo '</tr>';
As i currently wrote it, you may end up with an empty row at the end, if there are items in multiples of 3. But I'm mobile right now, so I'll leave that to you.
You can try below. Defined a variable and checks modulus (%) then print tr open/close accordingly. See the comment in the below code for more details.
$sql = $db->query('SELECT * FROM store_items WHERE store_cat = "Apparel"');
if(is_object($sql) && $sql->num_rows > 0)
{
$index = 0; // Define variable for store the indexes
while($row = $result->fetch_array())
{
if($index % 3 == 0) echo '<tr>'; // Check modulus (%) of $index. Open tr if the modulus is 0
echo '<td height="250">';
echo '<img src="" alt="" height="180" /><br />'.$row['store_name'];
echo '<br /><br />\$'.$row['store_price'].'<br />'.$row['store_desc'];
echo '<br /><href="">Add to Cart</a>';
echo '</td>';
$index++; // Increment the value of $index
if($index % 3 == 0) echo '</tr>'; // Check modulus (%) of $index. Close tr if the modulus is 0
}
}
If you want to print 4 columns then just change the checking if($index % 3 == 0) to if($index % 4 == 0)

PHP table alignment is not correct inside foreach Loop

I want to display Array data in a table with 3 columns in a row using foreach loop with a condition.
Coding
$value[]='a';
$value[]='b';
$value[]='c';
$value[]='d';
$value[]='e';
echo '<table width=30% border=1>';
echo '<tr>';
$counter=1;
foreach($value as $key){
if($counter>=3){ // if there is more than 3 elements, go to next Row
if($counter%3==0){ // when the Array hit 3th,6th,9th,12th.... element
echo '</tr><tr><td>';
echo $key;
echo '</td>';
}else{
echo '<td>';
echo $key;
echo '</td>';
}
}else{
echo '<td>';
echo $key;
echo '</td>';
}
$counter++;
}
echo '</tr>';
echo '</table>';
I double check the coding and didn't manage to find the error.... my output is the bottom of the image. However, the correct one should be top of the image. Please take a look at the photo
Anyone know what's wrong with my coding?
Change modulas condition with
if($counter % 3 == 1)
and you will get what you desire
You have "if counter >= 3" so you are hitting that condition on your 3rd element, not AFTER your third element.
Change the initialization of your counter to $counter=0;

How can I sort Items in a database created chart in PHP?

I have created a database which contains people from a run with the amount of rounds which they ran. After that I created this script which creates a html chart.
The script:
<?php
$db = new PDO("mysql:host=HIDDEN;dbname=HIDDEN", 'HIDDEN', 'HIDDEN') or die ("Verbindung nicht möglich");
$query_temp = $db->prepare("SELECT * FROM runners");
$query_temp->bindParam(':id', $id);
$id = 1;
$query_temp->execute();
echo '<table class="table table-hover">';
echo '<tr>';
echo '<th>ID</th>';
echo '<th>Name</th>';
echo '<th>Runden</th>';
echo '</tr>';
while($id_table = $query_temp->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
echo '<td>'.$id_table['runner_id'].'</td>';
echo '<td>'.$id_table['runner_name'].'</td>';
echo '<td>'.$id_table['runner_rounds'].'</td>';
echo '</tr>';
}
echo '</table>';
?>
The Database:
http://img.prntscr.com/img?url=http://i.imgur.com/WklMcTG.png
Screenshot how it looks:
http://img.prntscr.com/img?url=http://i.imgur.com/v2zbOSu.png
Now I want to give the users the ability to sort the people for their amount of rounds which they ran. Like the most person is at the first place. How can I do this?
To make this you need a js plugin and turn the HTML dynamic. There is a lot of plugins to make it and will list some of them to you:
datatables
tablesorter
Each plugin work differently, but in the end they have almost the same behaviour, then you need to check the documentation of them and try to run...
You should use DataTables with jQuery

php echo table with while loop

I am creating a table and want it laid out a certain way and have to retrieve the data from the DB. I am trying to get it set up where it has the usernames across the top example...
Jim Chris Allen Rick
7 8 4 5
my code looks like this and I have been messing around with it for hours and cant figure out why I cant get it set up how I want. Any help would be appreciated. Its a while loop.
while ($pickresults= mysql_fetch_assoc($picksquery)) {
//first row
echo '<th> '.$pickresults['username'].' </th> ';
echo ' <td> '.$pickresults['firstgame'].' </td> '; }
First off, you should learn the HTML code for tables. Your code is putting a Table Header (th) next to a normal column item (td). You need to loop through the headers first then next row loop through the column items or build the strings to echo out.
$headers = $col = "";
while($pickresults= mysql_fetch_assoc($picksquery)){
$headers .= "<th> {$pickresults['username']} </th>";
$col .= "<td> {$pickresults['firstgame']} </td>";
}
echo "<table><tr>$headers</tr><tr>$col</tr></table>";
Your structure is creating a TH then a TD and then a TH and then a TD etc.
This isn't how you create a table, you first need to make the four TH's and THEN you can make the four TD's.
Edit: Marko D has supplied the code to explain what I mean.
First collect table header and body, and then output them. The way you were doing, html was like this, I guess it's easy to see what is wrong with html
<th>name</th>
<td>value></td>
<th>another name</th>
<td>another value</td>
What you need is this:
$td = '';
$th = '';
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$th .= '<th> '.$pickresults['username'].' </th> ';
$td .= '<td> '.$pickresults['firstgame'].' </td> ';
}
echo '<table><tr>' . $th . '</tr><tr>' . $td . '</tr>' . '</table>';
You need to write all usernames in <th>-tags.
I'd put it in an array first, and from the array into the table...
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$picked[]=$pickresults;
}
echo "<table><tr>"; // create table and 1st row
foreach ($picked as $pick) {
echo "<th>{$pick['username']}</th>"; // create 1st line headers
}
echo "</tr><tr>"; // close 1st row and open 2nd
foreach ($picked as $pick) {
echo "<td>{$pick['firstgame']}</td>"; // create 2nd line...
}
echo "</tr></table>"; // close 2nd row and table

Adding extra table row

I'm stuck and can't figure this out.
I have this piece of code which is basically generating a table taking data from SQL cursor.
I need to add one extra table row <tr> (which will be filled with additional info) after each row. I've tried putting the new row in several places, but there is never any output data for it. This is someone else's code that I'm trying to modify.
$top_i=min($pagesize-1,$numrows-$start);
for($i = 0;$i<=$top_i;$i++) {
if (($i%2)==1)
echo "<tr class='saraksts_row0'>";
else
echo "<tr class='saraksts_row1'>";
$res=mssql_query("fetch absolute ".($start+$i)." from saraksts_cursor ");
$row=mssql_fetch_array($res);
$itemp = 0;
foreach($fields as $field) {
$key = $field[0];
if($field[2]) {
eval($field[2] );
}
$itemp++;
$val = ($row[$key] == "") ? " " : $row[$key];
// Get rid of right and left border, set topmost border
$st="";
if ($itemp==1)
$st.="border-left-style:none;";
if ($itemp==$numfields)
$st.="border-right-style:none;";
if ($i==$top_i)
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
$itemp = 0;
echo "</tr>\n";
}
The place where you want to add the extra row is after closing the first row and before the iteration moves to the next one. Note, it appears that you are doing some styling based on whether the row is odd or even. If you want this new row to have the same styling, I suggest you store the class you're applying to the preceding row so that you can also apply it to this row.
echo "</tr>\n";
echo "<tr><td>...</td><td>...</td></tr>\n"; /* Add the new row here */
}
...
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
//Here we go
echo '<td style="blah">'.$yourotherinfo.'</td>';
$itemp = 0;
echo "</tr>\n";

Categories