I have a table that get its rows from a MYSQL database
<table id="table1">
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_query("SET NAMES `utf8`"); // UTF 8 support!!
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr>
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
</table>
i have 2 css class called "A" and "B" for Odd Rows and Even Rows
i currently getting this done by replacing <tr> with <tr class='<?php echo $row['Row'].""; ?>'> and i have in my Database table a column "Row" which i add in A or B for even or odd row... the problem is if i wanna delete or add a new row between one of these i will have to change all the A and B in the other.
I have seen in another questions many way to do that in javascript or jquery but for a normal table with TR's which is not my case...(tried some of these scripts but couldn't get it fixed)
So what i want an easier way to do that Even and Odd rows, Thanks!
do it in CSS way (no inline class) once and for all:
in CSS:
#table1 tr:nth-child(odd) td { background-color:#ebebeb }
#table1 tr:nth-child(even) td { background-color:#0000ff }
in your HTML:
<table id="table1">
thats it, no matter if your table rows are removed/or not.
You can add those classes using jQuery easily like this
$(function(){
$('#table1 tr:odd').addClass('A');
// for even
$('#table1 tr:even').addClass('B');
});
Why didn't you use modulo in your while loop ? It's a better way than store your class in your database... :
$i = 0;
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr class="<?php echo $i%2 == 0 ? "class_A" : "class_B" ; $i++;?>" >
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
<?php
$class="odd"
while($row = mysql_fetch_array($rs)) {
$class = ($class=='even' ? 'odd' : 'even');
?>
<tr class="<?php echo $class">
...
</tr>
<?php } ?>
There are many ways to do this, PHP, Javascript and even pure CSS. Here's the PHP way to add a class to every other row:
while($row = mysql_fetch_blahblah()) {
$i = 0; ?>
<tr class="<?php echo $i % 2 == 0 ? 'class1' : 'class2';?>">
<td>....</td>
</tr>
<?php
$i++; // increment our counter
}
Basically the modulus operator returns the remainder of dividing the nubmers either side of it, so for example 3 % 2 == 1, 4 % 2 == 0, 5 % 2 == 1, so we can tell if $i is odd or even and alternate the classes added to the <tr>.
IMHO you want to either do it this way for 100% guarantee it will work (no browser dependencies) or if you design your app for modern browsers go for the CSS route.
Related
I display mysql table data using php.
I search but find solution for column but not for row.
Below I try to show what I want...
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<table>
<tr>
<td id="<?php echo $row["id"]; ?>"><?php echo $row["total"]; ?></td>
<td id="difference"> Difference from previous row. </td>
</tr>
<?php
$i++;
}
?>
</table>
<?php
$i=0;
$oldval = 0;
while($row = mysqli_fetch_array($result)) {
?>
<table>
<tr>
<td id="<?php echo $row["id"]; ?>"><?php echo $row["total"]; ?></td>
<td id="difference"> <?php echo ($i==0) ? $oldval : $row['total']-$oldval; ?> </td>
</tr>
<?php
$oldval = $row["total"];
$i++;
}
?>
</table>
$oldval variable is used to store current row's total field data so when you go to the next row, you can get the difference for current row because you have previous row's data stored in the $oldval
And the ternary condition I put there is because if $i==0 means the first row so you don't have any data of the previous row so by default difference is 0 and you can notice that I stored the current record's total field data after printing the difference
Im sorry if this has been answered before but I am new to PHP and MySQL and I can't figure this out.
Pretty much every time I alter my code to include an array I get a fatal error. What I am trying to do is display all the data in 3 columns from my table.
I have my site set up where you log in and I store that user's name as a "code" in a session. I have a table that has multiple user form entries that are differentiated by the user's code because in my form, I grab the code as a hidden field and add it to the entry in the table.
So far I have been able to isolate those entries by the users code, in one column I have the sum of all of the user's numerical data and I am able to echo this as a total.
I want the other 3 columns to display all the values in their columns and for each value have a line break in between them. And I am trying to print or echo these results in specific parts on a confirmation page.
I have seen examples with PDO using fetch_all and other examples of storing arrays but I can't seem to figure it out with my existing code.
Here is my existing code:
<?php
$user = *****;
$pass = *****;
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
$stmt = $dbh->prepare("SELECT sum(price),part_number,location,price FROM products WHERE code = :usercode");
$stmt->bindParam(':usercode', $_SESSION['MM_Username']);
if ($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
And here is where I want to display the results:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
</tbody>
</table>
Try like this:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><? echo $user['part_number']; ?></td><!--all column values-->
<td><? echo $user['location']; ?></td><!--all column values-->
<td><? echo $user['price']; ?></td><!--all column values-->
<td><? echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
There are a few things in your question that jumped out at me.
It looks like you're attempting to display both raw data (each row) and aggregate data (the sum of prices). It can be simpler to fetch the information separately instead of in the same request.
You had mentioned fetch_all in PDO, but the method is fetchAll.
Instead of working with PDO within the HTML (like iterating through while calling fetch), write code so that you're simply iterating over an array.
Based on your description of the problem, it sounds like you want to separate the total price from the raw data, so you can reduce your table down to three columns and use the table footer to show the total price.
Based on those, I have the following solution that
Separates the calls to get data into descriptive functions
Use money_format to better display prices
Removes any database-specific manipulation from the view itself.
<?php
function getTotalPriceForUser(PDO $database_handler, $user_code)
{
// If no rows are returned, COALESCE is used so that we can specify a default
// value. In this particular case, if there aren't any products that would
// match, we'd still get a result with a value of 0.
$sql = 'SELECT COALESCE(SUM(price), 0) FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// This fetches the first row of the result; the result is given as an array with numerical keys.
$result = $stmt->fetch(PDO::FETCH_NUM);
// [0] refers to the first column
return $result[0];
}
function getProductsForUser(PDO $database_handler, $user_code)
{
$sql = 'SELECT part_number, location, price FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// fetchAll returns all rows, with each row being an associative array (where part_number, location and price are the keys)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Set up the database information
$user = '*****';
$pass = '*****';
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
// money_format to use the below money formatting; this makes sure there's a dollar sign to represent USD, for example
setlocale(LC_MONETARY, 'en_US.UTF-8');
// Store $_SESSION['MM_Username'] in a local variable
$user_code = $_SESSION['MM_Username'];
// Get the list of products associated with this user code
$products = getProductsForUser($dbh, $user_code);
// Get the total cost of the products
$total_cost = getTotalPriceForUser($dbh, $user_code);
?>
<table style="margin:0 auto;" cellspacing="7" width="100%">
<thead>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<td style="text-align: right" colspan="2">Total:</td>
<td style="text-align: right; border-top: 1px solid #999"><?= money_format('%.2n', $total_cost) ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach($products as $product): ?>
<tr>
<td><?= $product['part_number'] ?></td>
<td><?= $product['location'] ?></td>
<td style="text-align: right"><?= money_format('%.2n', $product['price']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Change to this
<? echo
to
<?php echo
Try this:
...
$keys = array_keys($user);
foreach ($keys as $k) :
?>
<td><?= $user[$k]?></td>
<?php endforeach?>
<table>
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
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.
I am using this code to create an infinite table for my mysql queries:
<table cellspacing='0'> <!-- cellspacing='0' is important, must stay -->
<!-- Table Header -->
<thead>
<tr>
<th>User</th>
<th>SteamID</th>
<th>Banned by</th>
<th>Admin SteamID</th>
<th>Time Banned (min)</th>
<th>Reason</th>
</tr>
</thead>
<!-- Table Header -->
<!-- Table Body -->
<tbody>
<?php
echo '<tr>';
for($i = 0; $bans = mysqli_fetch_array($query2); $i = ($i+1)%3){
echo '<td>'.$bans['name'].'</td>';
echo '<td>'.$bans['steamid'].'</td>';
echo '<td>'.$bans['nameAdmin'].'</td>';
echo '<td>'.$bans['steamidAdmin'].'</td>';
echo '<td>'.$bans['time'].'</td>';
echo '<td>'.$bans['reason'].'</td>';
if($i == 2)
echo '</tr><tr>';
}
echo '</tr>';
?>
</tbody>
I got that code from Mysql fetch array, table results
It works fine, except it doesn't CORRECTLY go further down than 6 rows. The other rows for whatever reason are placed to the right of my last column as shown in this screenshot:
http://puu.sh/h0qZF/a12de1dd87.png
How can I fix this? Is there something wrong with my code? Why is it happening?
Well, your looping makes no sense. Using $i to inject new rows, like is done here, is not necessary; you can just loop over each row and then output it as a row:
<table>
<!-- <thead>...</thead> -->
<tbody>
<?php while ($bans = mysqli_fetch_array($query2)): ?>
<tr>
<td><?php echo $bans['name'] ?></td>
<td><?php echo $bans['steamid'] ?></td>
<td><?php echo $bans['nameAdmin'] ?></td>
<td><?php echo $bans['steamidAdmin'] ?></td>
<td><?php echo $bans['time'] ?></td>
<td><?php echo $bans['reason'] ?></td>
</tr>
<?php endwhile ?>
</tbody>
</table>
You are making two columns.
You have code that will print out the end of the table row every two sets of data:
if($i == 2)
echo '</tr><tr>';
It should just be echo '</tr><tr>';
Use a while loop as instructed here . So something like this:
$result = $conn->query($sql);
while($bans = $result->fetch_assoc()) {
echo '<td>'.$bans['name'].'</td>';
echo '<td>'.$bans['steamid'].'</td>';
echo '<td>'.$bans['nameAdmin'].'</td>';
}
I will be generating a HTML table with data pulled from MySQL.The number of rows in my MySQL table are not fixed.
<?php
while($row=mysql_fetch_assoc($result))
{ ?>
<tr>
<td><?php echo $row['col1'];?></td>
<td><?php echo $row['col2'];?></td>
</tr>
<?php } ?>
Now how do I have the table rows and table data elements assigned unique id ??
Another loop to generate them won't work as I can't set an exit condition for the new loop as number of rows are not fixed.
Please guide me as to how to go forward about it. I can only use Javascript and not JQUERY.
Why can't you do something like this ?
<?php
$i = 1;
while($row=mysql_fetch_assoc($result))
{ ?>
<tr id="row<?php echo $i;?>">
<td id="cell-left-<?php echo $i;?>"><?php echo $row['col1'];?></td>
<td id="cell-right-<?php echo $i;?>"><?php echo $row['col2'];?></td>
</tr>
<?php
$i++;
} ?>
Please note, I have added ids row, cell-left- and cell-right- by myself. You may change them as per your requirements.
You can use a counter when iterating through the rows, maybe something like this:
<?php
$rowCount = 0;
while($row=mysql_fetch_assoc($result))
{
$rowCount++;
?>
<tr id="<?php echo 'row' . $rowCount;?>">
<td><?php echo $row['col1'];?></td>
<td><?php echo $row['col2'];?></td>
</tr>
<?php
}
?>
You can now select an element with
var rowID = 1;
document.getElementById("row" + rowID);
Hope this helps.