I have a database that contains donor information and then have PHP pages that pull that data and display it under the donor's specific category.
The code I am using is as follows:
// 10,000 DONORS
echo "<p><b>$10,000 cont.</b></p>";
$sql = "SELECT * FROM donor WHERE DonationAmount = 10000 AND Category = '1' or DonationAmount = 10000 AND Category IS NULL ORDER BY LastName ASC LIMIT 10000 OFFSET 6";
$result = mysqli_query($conn, $sql);
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if (empty($row['DisplayName'])) {
// it's empty!
if (empty($row['FirstName'])) {
echo $row['LastName'];
}
else {
echo $row["LastName"] . ", " . $row["FirstName"];
}
} else {
// Do stuff with the field
echo $row["DisplayName"] . "";
}
echo "</td>";
$i++;
if ($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
} else {
} echo "</tr></table>";
My question is as follows: right now the names are inserted into the table in a manner that makes the read left->right->left->right etc. I need them to show up like a normal list works and reads top to bottom, and rolls to the next column when it is told to (counter?). How can I do this?
Here is a preview off the page
EDIT: tried this code:
$sql = "SELECT * FROM donor WHERE DonationAmount = 1000 AND Category = '1' or DonationAmount = 1000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
$i = 0;
$count = 0;
$total_rows = $result->num_rows;
$halfsize = $total_rows / 2;
$FirstArray = array();
$SecondArray = array();
while ($row = mysqli_fetch_assoc($result)){
while ($count <= $halfsize){
$FirstArray[] = $row['DisplayName'];
//echo "$FirstArray[$count]";
$count++;
}
$SecondArray[] = $row['DisplayName'];
//echo "$SecondArray[$count]";
}
echo "<table>";
for($j=0; $j<count($FirstArray); $j++){
echo "<tr><td>". $FirstArray[$j] . "</td><td>" . $SecondArray[$j] . "</td> </tr>";
}
echo "</table>";
And I just get the same field (the first result) for all of the first column (The First Array?) and then the second column (SecondArray) contains all of the results.
Your issue is not your PHP or your MySQL but your output handling.
So there's an array of data that's being dumped on your HTML and you need to order it to look nice . Two columns reading left to right in a table format.
The <table> tag is perfect for this, and while most people hate the table tag, it is useful for tabled data.
It's worth noting that due to the flexibility and accommodating nature of CSS/HTML that this is not the only correct way but one of many ways this issue can be addressed
Method:
You have a while loop outputting one unit at a time, a unit in this case being a name in a <td></td> block. So that's your unit:
while {
print "unit";
}
So if you have two columns you want to arrange then you need to tell the while loop to distinguish between the first and the second column, this can be done with detecting if the counter (+1 for each itteration) is odd or even.
You can do this with the modulus divisor in PHP:
while {
counter++
if (counter%2) == 1 ){
//odd number.
}
}
So to sum it all up and give you a basic example:
$output = "";
$rowsTotal = mysqli_num_rows($result); //from your original code.
$counter = 0;
while ($row = mysqli_fetch_assoc($result)) {
$counter++; //plus 1 each itteration
if (($counter%2) == 1){
/// is odd so open the row of the table.
$output .= "<tr>";
}
$output .= "<td>";
if (empty($row['DisplayName'])) {
// it's empty!
if (empty($row['FirstName'])) {
$output .= $row['LastName'];
}
else {
$output .= $row["LastName"] . ", " . $row["FirstName"];
}
}
else {
// Do stuff with the field
$output .= $row["DisplayName"] . "";
}
$output .= "</td>";
if (($counter%2) == 0){
// if even so close the row of the table.
$output .= "</tr>";
}
// special case: If there area total of odd number of outputs
if($counter == $rowsTotal && $counter%2 == 1){
// so the last counter value is an odd number so force closure
// of </tr> (or add a blank space)
$output .= "<td> </td></tr>
}
} //end while.
...
print "<table>";
print $output;
print "</table>";
I don't want to dive deep into getting really creative with CSS but you can use CSS to finesse and improve the core HTML output setout above with some wonderful Cascading Style sheets, but above is a very rough outline of the sortof approach you could use to simulate a base level intelligence for the script to output names in the layout you are looking for.
Good luck.
CSS example:
table td {
background-color:#000;
color: #fff;
font-size:1.5rem;
text-align:left;
width:49%; /* 50% sometimes causes overflow, so set a tiny bit smaller */
padding:0.25rem;
margin:0;
box-sizing: border-box;
}
VERSION 2
From comments, OP Needs the results from the SQL query to be two columns, rather than two rows. This means that table (a row structure) is inappropriate for this output and so instead we should use a more customised CSS / div tag set:
The layout would be two columns of approximatly 49% width each, and then each column contains block elements, This blob of blocks will then need to be split in half and a divider added to generate two shorter columns from one long one.
The block elements are output in a foreach loop and once the halfway point is met then an extra HTML code is inserted to break the elements up into a second <div> . this is a little bit hacky it feel to me, but, does the job.
requirements:
A predefined counter of result rows. One can easily be generated. And that the SQL query is already ordered in the intended way, using MySQL ORDER BY.
Semi-Pseudo code:
$array = SQL data result.
$counter = counter of how many array rows are returned.
$divisorCount = ceil($counter /2);
$foreachCount = 1
foreach ($array as $row){
$foreachCount++;
$block[] = "<div class='block'>".$row['data']."</div>\n";
if($foreachCount > $divisorCount){
$foreachCount = 0; //reset, as this will not be true again.
end($block);
$key = key($block); //most recent block array reference.
$block[$key] .= "</div><div class='column'>"; //the insert.
}
}
unset($row,$key,$foreachCount,$divisorCount); //tidyup.
The above generates a bunch of array elements, one for each name. There is an inserted splitter that ends the initial column and starts a second column, finally we wrap the whole block array into a final <div> wrapper.
$output = "<div class='tableContainer'>
<div class='column'>".implode($block)."</div>
</div>";
The above output will be the opener for the first column but the closer for the second column. Within output we now have the complete columns for two columns of all results contained in a Div Container element.
The following CSS classes would need some tweaking to get right but should be a start:
CSS
.block{
line-height: 2rem;
display:block;
padding:0.25rem;
box-sizing:border-box;
}
.column{
width: 49%;
min-width:150px; /* or whatever. */
display:inline-block;
}
.tableContainer{
max-width: 800px; /* or whatever. */
min-width: 300px; /* or whatever. */
width:100%;
margin:auto; //centres it.
}
The CSS would be 49% rather than 50% because box sizes can have a tendancy to overflow on different browsers (Firefox especially), but the $output would finally be:
HTML
<div class='tableContainer'>
<div class='column'><div class='block'>My Name</div>
<div class='block'>Your Name</div>
<div class='block'>His Name</div></div>
<div class='column'><div class='block'>Their Name</div>
<div class='block'>Her Name</div>
<div class='block'>Smacked HorseBombs</div>
</div>
</div>
You could also possibly substitute display:inline-block for float:left, but thats the basics, have a play on jsfiddle to tweak as you need.
I won't use tables for this. There may be some other css tricks. But for the sake of question, I'm answering.
Create two arrays.
Get the size of resultset with mysqli_num_rows, and divide it by two, then walk through this first array and move them until halfsize into array1. And then remainig into array2.
At the end you'll have something like this
Array 1 Array 2
------- -------
[0] Row 1 [0] Row 4
[1] Row 2 [1] Row 5
[2] Row 3
Then walk through it and fill your html table. (with controlling them against being empty)
for($i=0; $i<count($array1); $i++){
echo '<tr><td>'.$array1[$i].'</td><td>'.$array2[$i].'</td></tr>';
}
Related
I have a database where teams will have multiple entries each with different locations. Each entry will have a team name. So for example, team1 might appear several times but each time the location will be different.
The structure of the DB is (each of these represents a column header):
team_name, first_name, last_name, location, arrival_time
My current working code creates HTML tables grouped by team name but currently only creates one row to show the first location and the time of arrival for the first location. I need this to dynamically create more rows to show all locations and arrival times for each team.
The desired result would look like this -
https://codepen.io/TheBigFolorn/pen/LqJeXr
But current result looks like this -
https://codepen.io/TheBigFolorn/pen/qgMppx
And here is an example of how the DB table might look -
https://codepen.io/TheBigFolorn/pen/daqJze
I've tried breaking up the echo and adding a second while loop before the row that I want to apply the above logic to but it seems to break everything. Any input on how I get this to work without having to use separate queries for each team would be very much appreciated. I'm new to php so please go easy on me :)
<?php
$leaders = "SELECT *, COUNT(location) FROM my_example_table GROUP BY team_name";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='red-border'>
<h2>". $row["team_name"]. "<br><small>Total locations visited: ". $row["COUNT(location)"]. "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>
<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>
</table>
</div>
";
}
} else {
echo "0 results";
}
?>
Your problem is due to the GROUP BY, as you've probably realised. This is necessary in order to get a count per team, but causes the number of rows output to be only 1 per team - that's what grouping does. Fundamentally, running an aggregate query such as a COUNT or SUM is incompatible with also outputting all of the row data at the same time. You either do one or the other.
Now, you could run two queries - one to get the counts, and one to get all the rows. But actually you don't really need to. If you just select all the rows, then the count-per-team is implicit in your data. Since you're going to need to loop through them all anyway to output them in the HTML, you might as well use that process to keep track of how many rows you've got per team as you go along, and create the "Total number of locations" headings in your HTML based on that.
Two things are key to this:
1) Making the query output the data in a useful order:
SELECT * FROM my_example_table Order By team_name, arrival_time;
2) Not immediately echoing HTML to the page as soon as you get to a table row. Instead, put HTML snippets into variables which you can populate at different times in the process (since you won't know the total locations per team until you've looped all the rows for that team), and then string them all together at a later point to get the final output:
$leaders = "SELECT * FROM my_example_table Order By team_name, arrival_time;";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
$currentTeam = "";
$locationCount = 0;
$html = "";
$teamHtmlStart = "";
$teamHtmlEnd = "";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
//run this bit if we've detected a new team
if ($currentTeam != $row["team_name"]) {
//finalise the previous team's html and append it to the main output
if ($currentTeam != "") $html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
//reset all the team-specific variables
$currentTeam = $row["team_name"];
$teamHtmlStart = "<div class='red-border'><h2>".$currentTeam."<br><small>Total locations visited: ";
$locationCount = 0;
$teamHtmlEnd = "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>";
}
$teamHtmlEnd .= "<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>";
$locationCount++;
}
//for the final team (since the loop won't go back to the start):
$html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
echo $html;
}
else {
echo "0 results";
}
Here's a runnable demo (using some static data in place of the SQL query): http://sandbox.onlinephpfunctions.com/code/2f52c1d7ec242f674eaca5619cc7b9325295c0d4
is it possible to force a table to display e.g. 10 rows - no matter what, even if the rows are blank?
my code is as so:
<table>
<tr>
<th>Title</th>
<th>Date Created</th>
</tr>
<?php
try {
$pages = new Paginator('10','p');
$stmt = $db->query('SELECT postID FROM article_posts');
$pages->set_total($stmt->rowCount());
$stmt = $db->query('SELECT * FROM article_posts ORDER BY postID DESC '.$pages->get_limit());
while($row = $stmt->fetch()){
echo '<tr>';
echo '<td>'. $row['postTitle'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
echo '</td>';
echo '</tr>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
</table>
<?php echo $pages->page_links(); ?>
i have the records output and pagination into rows of 10, however, if there is a number such as 26 records, then i get just six rows on one page.
its more of a design frustration of mine for wanting to do this as the page alters (everything moves up) and i want everything to keep form. i guess i could put the table inside a fixed div to prevent this, but would like to know if this way is possible, and i guess is it a 'bad' way to do this over selecting the div method. i am thinking of in the future allowing the user to increase/decrease the amount of results shown, so e.g. 10, 20, 50... would forcing the table to display a set number of rows be a 'bad' idea when approaching this?
To expand on Charlotte's comment, this is a way of doing it:
$i = 0;
while($row = $stmt->fetch()){
echo '<tr>';
echo '<td>'. $row['postTitle'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
echo '</td>';
echo '</tr>';
$i++;
}
while ($i < 10){
echo '<tr><td></td><td></td></tr>';
$i++;
}
There are two issues here. First, if table cells are completely empty, their height is by default zero. You can fix this by setting height on them; for cells, it acts as minimum height. For brevity, I’ll use just 4 rows here.
body {
line-height: 1.3; /* set to a specific value */
}
.x td {
height: 1.3em; /* one line, since line height is 1.3 */
}
<table border>
<tr><td>foo</td>
<tr><td>bar</td>
<tr><td></td>
<tr><td></td>
</table>
Same with min height set:
<table border class=x>
<tr><td>foo</td>
<tr><td>bar</td>
<tr><td></td>
<tr><td></td>
</table>
The other issue is the amount of tr elements in tables. This is best handled in the generation process by just keeping track of the amount of rows and emitting some empty rows when needed. You might then consider including no-break spaces as content, e.g. ` , since it causes the cells to have the height of one line, and you would not need the CSS code.
Firstly let me apologise for my vague question title, this is my first post on this site; after spending 2 days searching for the answer to my question (and getting quite close in some cases) I've hit a wall. Normally I can find everything I need from stackoverflow but this time I've run out of ways to word my question in the search bar.
I have a mysql table containing data for clothes (tbl_clothing) and in this table (I've simplified this for my problem) I have columns: style, colour_url, size, carton_price
The 'style' is for a particulate type of garment $row['style'] in the first sql statement comes from the initial request to the database to find out if the users choice is actually a valid choice (don't worry I've sanitized it, no direct user input is ever used!)
I am grouping by colour_url to create an array of all the colour variations for the chosen style. Incidentally the colour_url is also the actual url to the image file for that colour (used later). Yes this does mean that in the database there is repeating data, the colour_url is repeated as many times as there are sizes for that colour - I've inherited it and can't change that yet.
I then iterate over this array 'foreach' of the different colours and perform another DB lookup to select all sizes and prices for the chosen style and the current colour.
Still in the above foreach loop I perform a while loop to create a second array to hold the sizes and prices (multiple rows are returned from the DB).
Still in the above foreach loop I perform another foreach loop on the second array to create the table structure for outputting.
This is now screaming at me that it is not the best way of achieving what I'm tying to do.
Am I just over thinking this or is there a much simpler way of doing things? I've tried doing a single sql lookup to retrieve a multidimensional array all in one hit but then cant separate out the data into correct groups I've been over and over transposing arrays re-looping through the array creating other "reference" arrays all without any success.
The basic logic works like this:
1 style = many colours
1 colour = many sizes
1 size = 1 price
And i'm trying to get a table output (for each colour) like this:
_________________________________
| (IMG A) | Size(1) | Size(2) | Size(3) |
| colour_A | Price(1) | Price(2) | Price(3) |
|_________|_______________________|
_________________________________
| (IMG B) | Size(1) | Size(2) | Size(3) |
| colour_B | Price(1) | Price(2) | Price(3) |
|_________|_______________________|
Here is my code, it does the job but this cant be the best way to do it:
$sql = "SELECT colour_url FROM tbl_clothing WHERE style = '".$row['style']."' GROUP BY colour_url";
$result = $mysqli->query($sql);
$numRows = $result->num_rows;
if ($numRows != 0){
while ($rowS = $result->fetch_assoc()){
$aResults[] = $rowS['colour_url'];
}
$result->free();
foreach ($aResults as $k=>$v){
echo "<table><tr><td rowspan='2'><img title='' alt='' src='".$v."' /></td>";
$sql = "SELECT size, carton_price FROM tbl_clothing WHERE style = '".$row['style']."' AND colour_url = '".$v."'";
$result = $mysqli->query($sql);
$numRows = $result->num_rows;
if ($numRows != 0){
$aSizePrice = array();
while ($rowS = $result->fetch_assoc()){
$aSizePrice[$rowS['size']] = $rowS['carton_price'];
}
$sizes = "";
$prices = "";
foreach ($aSizePrice as $key=>$val){
$sizes .= "<td>".$key."</td>";
$prices .= "<td>".$val."</td>";
}
}
$result->free();
echo $sizes;
echo "<tr>".$prices."</tr>";
echo "</tr></table>";
}
}
?>
Any help would be a hugely appreciated, even just a point in the right direction, a different opinion or even a sarcastic comment will do at this point...
One thing i might recommend right off the bat, seperate your concerns. You are trying to get data right from the database into your view layer. Instead, get your data, compile it into memory, THEN, display it. It will make your problem easier to solve right off the start.
For example:
//Prepare the data receptacle
$data = array();
//Query to data to work with
$result = $mysqli->query("SELECT * FROM tbl_clothing WHERE style = '".$row['style']."'");
$numRows = $result->num_rows;
while ($rowS = $result->fetch_assoc()){
//Make sure our data can be stored correctly into our structure
if(!isset($data[$row['style']])){ $data[$row['style']] = array(); }
if(!isset($data[$row['style']][$rowS['colour_url'])){ $data[$row['style']][$rowS['colour_url'] = array(); }
if(!isset($data[$row['style']][$rowS['colour_url']['sizes'])){ $data[$row['style']][$rowS['colour_url']['sizes'] = array(); }
if(!isset($data[$row['style']][$rowS['colour_url']['prices'])){ $data[$row['style']][$rowS['colour_url']['prices'] = array(); }
//Store the price and size
$data[$row['style']][$rowS['colour_url']['sizes'][] = $rowS['size'];
$data[$row['style']][$rowS['colour_url']['prices'][] = $rowS['carton_price'];
}
//At this point we have our data, let's just show it
?>
<table>
<?php foreach($data as $style => $color_urls){ ?>
<?php foreach($color_urls as $color_url => $content){ ?>
<tr>
<td rowspan="2">
<img title="" alt="" src="<?php echo $colour_url; ?>" />
</td>
</tr>
<tr>
<?php foreach($content['sizes'] as $size){ ?>
<td><?php echo $size; ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach($content['prices'] as $price){ ?>
<td><?php echo $prices; ?></td>
<?php } ?>
</tr>
<?php } ?>
<?php } ?>
</table>
This is just a quick draft, i might not have understood your question correctly, you'll have to fix the errors and the miscomprehensions yourself. At least you have a good start with this!
Well, let's start with your query. In your first query, you claim you're trying to get all of the colors for a given style. You can use the DISTINCT keyword for that
SELECT DISTINCT colour_url
FROM tbl_clothing
WHERE style = ?
But that's not what you're actually looking to get - you actually want all of the color/size combinations in your database for a given style, which you would likely want to select thusly:
SELECT colour_url, size, carton_price
FROM tbl_clothing
WHERE style = ?
Once you've done that, you want to parse it into a data structure. (you should be parameterizing your queries - I recommend the PDO library, so I'll show you how that would work).
<?php
$db = new PDO('connection', 'user', 'pass');
$query = $db->prepare('SELECT colour_url, size, carton_price
FROM tbl_clothing
WHERE style = :style');
$query->bindValue(':style', $row['style'], PDO::PARAM_STR);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$clothes = array();
foreach($results as $result){
if(!isset($clothes[$result['colour_url']]))
$clothes[$result['colour_url']] = array();
$clothes[$result['colour_url']][$result['size']] = $result['carton_price'];
}
?>
Your results are now in a series of nested maps - from $clothes[$color], you get a map from size to price. $clothes[$color][$size] will net you the price of a specific color and size, and you can choose to print them that way:
<?php
foreach($clothes as $color => $prices) {
$sizeStr = '<td>' . implode('</td><td>', array_keys($prices)) . '</td>';
$priceStr = '<td>' . implode('</td><td>', $prices) . '</td>';
?><table>
<tr>
<td rowspan="2">
<img title="" alt="" src="<?=$color?>" />
</td>
<?= $sizeStr ?>
</tr>
<tr>
<?= $priceStr ?>
</tr>
</table><?php
}
?>
Your code now reads a lot closer to english, which will make it easier to debug, and easier to pas on to others.
I have a table with a row of 3 div's then another row or 3 div's then another and then another.
But what I'm trying to achieve is to highlight every other row. And each row contains 3 div's.
So the first row will be .mydiv .even and then the .even's will be grey. Then the next row will be .mydiv .odd and then the .odd's will be white.
I am using this code from css-tricks.com ($xyz++%2) to make every other div a different class.
All help is apreciated.
This is my code
$get_new_games = mysql_query("SELECT game_title,game_description,id from games ORDER BY added_date LIMIT 10");
while ($row = mysql_fetch_array($get_new_games)) {
$new_game_title = $row['game_title'];
$new_game_description = $row['game_description'];
$new_game_id = $row['id'];
$new_games_display .= '<div class = "game_module class-'.($xyz++%2).'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
}
It would make more sense to add the class to the row, to output the table rows in PHP, use something like this:
<?php for ($i = 0; $rows[$i]; $i ++): ?>
<tr class="<?php echo $i % 2 ? 'odd' : 'even'; ?>">
<td>
<div />
</td>
<td>
<div />
</td>
<td>
<div />
</td>
</tr>
<?php endfor; ?>
The modulo operator % will return the remainder of the division, in this case the division is by two and any equal number will give a remainder of zero, and any unequal number will give a remainder of one.
The selector for the div would then be:
tr.odd td > div
tr.even td > div
this will make sure that only the top div in each row is selected.
UPDATE:
From the code you've supplied it doesn't really appear you're using a table at all (maybe you meant it in a looser sense than the actual HTML element?). Going by your code you already use the modulo in the way described above, but you need to change the following.
$xyz = 0;
$get_new_games = mysql_query("SELECT game_title,game_description,id from games ORDER BY added_date LIMIT 10");
while ($row = mysql_fetch_array($get_new_games)) {
$new_game_title = $row['game_title'];
$new_game_description = $row['game_description'];
$new_game_id = $row['id'];
$new_games_display .= '<div class = "game_module class-'.($xyz++%2 ? 'odd' : 'even').'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
}
I've added the first line to initialize the variable to zero and changed the $new_games_display-line to ($xyz++%2 ? 'odd' : 'even'). This will ensure that every other div has the class class-odd and the rest class-even.
The only issue I'm having is that the code you supplied doesn't really correspond to your initial problem, with rows of three divs, maybe I'm missing something -- feel free to supply more code and I'll be able to help you more.
While looping through and printing out the rows, you will use the index to determine even or odd.
if(!$index%2){
echo "even";
}
else{
echo "odd";
}
The % is the modulus operator, which returns the remainder when its operands are divided.
Edit:
So in your case, your last line would be
$new_games_display .= '<div class = "game_module class-'.(($xyz++%2) ? 'odd' : 'even').'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
try some thing like this:
$i = 0;
while ($row = mysql_fetch_array($get_new_games))
{
...
$i++;
$class = ($i%2)? "even" : "odd";
$new_games_display .= '<div class = "game_module class-' . $class .'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
}
instead of check $i%2 ==0 or not you can use something like
$class = ($i & 1) ? "odd" : "even";
or
if($i & 1){
$class = "odd";
}else{
$class = "even";
}
Your code is only highlighting every other row instead of groups of three rows. You could use an :nth-child css selector, but using php will ensure browser compatibility since the class is hard coded. Anyway..
$evenodd = false; // false indicates odd
$count = 0;
while (...) {
... //display
$count++;
if ($count == 2) {
$evenodd = !$evenodd;
$count = 0;
}
}
My Website
As you can see on the above link there are several 'kids', the information for each one is grabbed from a database.
I want to make each alternating image float to the left, so that the images go left, then right, then left etc. At the moment they all float left. This is what I have so far:
<?php
$query="SELECT id, title, text, media, media2, thumb, deleted FROM kids ORDER BY id DESC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){
if($row['deleted'] == 0) {
echo '<div id="'.$row['title'].'">';
echo '<img src="images/'.$row['media'].'" class="floatLeftClear" id="border" />';
if($row['media2'] != "") {
echo '<img src="images/'.$row['media2'].'" class="floatLeftClear" id="border" />';
}
echo '<p id="text">';
echo '<span class="kisstitle">'.$row['title'].'</span><br>';
echo $row['text'];
echo '</p>';
echo ' <p align="center" id="spererater"><img src="images/seperater.jpg" width="900" height="5" />Top<br /></p>';
}}
?>
I tried to check the ID, if even, float left, if odd, float right, but I couldn't work out how to do it, plus the ID may not always be even / odd alternating so I'd rather find a different solution if possible.
Use a counter variable, increment by one each time you're looping over an item -- and use that counter with a modulo, to determiner whether you are on an even or odd line :
$counter = 0;
while($row = mysql_fetch_array($result)){
if (($counter % 2) == 0) {
// even
} else {
// odd
}
// use the data of the current $row, display it
$counter++; // increment the counter, for next iterator
}
Add a counter. Before loop $i = 0; and inside loop $i++, if ($i % 2 == 0) { // odd} else {// even}