I'm trying to display the first row in one color and the second row in another color but my code displays the result twice in both colors for example lets say I have 5 results my code will double the results by displaying 10 results. How can I fix this problem?
Here is the php code.
while ($row = mysqli_fetch_assoc($dbc)) {
//first row
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
//second row
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
You need to change the class on each row:
$count = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if( $count % 2 == 0 ) {
$classMod = '';
} else {
$classMod = '-2';
}
//first row
echo '<h3 class="title' . $classMod . '">' . $row['title'] .'</h3>';
echo '<div class="summary' . $classMod . '">' . substr($row['content'],0,255) . '</div>';
$count++;
}
your code should be like this
CSS
.odd { background: #CCC }
.event { background: #666 }
PHP
$c = true;
while ($row = mysqli_fetch_assoc($dbc)) {
$style = (($c = !$c)?' odd':' even');
echo '<h3 class="title '.$style.'">' . $row['title'] .'</h3>';
echo '<div class="summary '.$style.'">' .substr($row['content'],0,255) . '</div>';
}
Here's a solution with minimal repetition:
$count = 0;
while (($row = mysqli_fetch_assoc($dbc)) && ++$count) {
printf(
'<h3 class="title%1$s">%2$s</h3>'
. '<div class="summary%1$s">%3$s</div>'
, $count % 2 ? "" : "-2"
, $row['title'] // might want to use htmlentities() here...
, substr($row['content'], 0, 255) // and here...
);
}
$i = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
$color =$i % 2;
echo '<h3 class="title-' .$color . '">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
$i++;
}
Your code just displays every result twice. Use a conditional (e.g. an integer or a boolean) to switch between rows (like: if true, then green; if false, then red).
For a boolean you could change the current value like so:
bool = !bool;
Couple of extra points:
You don't (normally) need so many classes. If you have <div class="stripe"> as your container, you can target the items with e.g. .stripe h3 in CSS.
If you target the odd and even items in CSS with .stripe h3, you can then overwrite just the odd items.
In a perfect world, you should keep presentation in the CSS. All browsers but IE7 and below support div:odd to target any odd child of a parent. This may require changing the structure of your HTML slightly. For IE7 and below, I'd add classes with JavaScript instead of PHP. When IE7 is no more then you can just remove the JS.
By the way, you could do this code too:
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
if($row = mysqli_fetch_assoc($dbc)){
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
}
IMO, there is no excuse for not delegating this kind of non-critical, presentation layer decoration to client side code.
Just use a library like jQuery and access the odd and even rows like so:
<script>
$(document).ready(function()
{
//for your table rows
$("tr:even").css("background-color", "#F4F4F0");
$("tr:odd").css("background-color", "#EFF1F2");
});
</script>
You'll have us generating font tags next.
Related
Forgive me if this is simple but I have a for each loop that searches JSON data for results from a search. I then have some preg_match statements that will look at some of the tags within the JSON and if their is a match display the thumbnail in a div. and currently this all works. But it currently displays every result in its own Div and i want just five divs with multiple images within if there is a match.
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
if(preg_match("/_cm/i",$target)) {
echo '<div id="div5">';
echo '<h2>Creative</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SS/i",$target)) {
echo '<div id="div6">';
echo '<h2>Styled</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SH/i",$target)) {
echo '<div id="div7">';
echo '<h2>Group</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/still life/i",$target1) && preg_match("/_sm_00|_sd_00/i",$target)) {
echo '<div id="div8">';
echo '<h2>Cutout</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/worn/i",$target1)) {
echo '<div id="div9">';
echo '<h2>Worn</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
}
I cant quite figure out how to accomplish this, would it be the case of putting the results into an array and then displaying the results within the div?
Any help would be greatly appreciated.
You are right and answered the question yourself :)
Collect the results in a first step and create the markup in a second step. Something like this will do it:
$creative = [];
$styled = [];
/* ... */
function getHitInfos($theHit)
{
return [
"url" => $theHit->thumbnailUrl,
"name" => $theHit->metadata->baseName
];
}
function printResults($results, $title) {
echo '<div>';
echo '<h2>'.$title.'</h2>';
foreach ($results as $key => $val) {
echo "<img src='" . $val["url"] . "' alt='error'>";
echo $val["name"];
}
echo '</div>';
}
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
echo '<div>';
if(preg_match("/_cm/i",$target)) {
$creative[] = getHitInfos($hit)
}
if(preg_match("/_SS/i",$target)) {
$styled[] = getHitInfos($hit)
}
/* ... */
}
printResults($creative, "Creative");
printResults($styled, "Styled");
/* ... */
Disclaimer: My last contact with php is some years ago, but I hope you will see the point here.
(I also created some helping functions to DRY the code)
I am currently trying to create a class schedule which I pull from my Sql Server database with PHP and I am trying to get the layout output as well as the data as I am grouping the resources.
These groupings are nested such as:
-DAY
--TIME
---CLASS
----STUDENTS
And should output like this:
However, I am getting this:
My current output is working, however, it is only on the first loop, then everything goes haywire. I am assuming there is an erroneous </div> tag somewhere in my code yet I cannot for the life of me find it.
My php code is a function that is delcare as such:
<div class="mainScheduleWrapper">
<?php daySchedule(); ?>
</div>
My php code is as such:
function daySchedule() {
global $conn;
$dayScheduleQuery = 'SET DATEFIRST 1
SELECT [DAY].[DAY] AS [DAY], CLASS.CLASSTIME AS CLASSTIME, CLASSLEVEL.CLASSLEVEL AS CLASSLEVEL, CLASS.MAXSTUDENT AS MAXSTUDENT, INSTRUCTOR.FIRSTNAME AS INSTRUCTOR, STUDENT.FIRSTNAME AS STUDENTFIRST, STUDENT.SURNAME AS STUDENTLAST, STUDENT.DOB AS STUDENTDOB
FROM STUDENT JOIN BOOKING ON STUDENT.ID = BOOKING.STUDENTID JOIN CLASS ON CLASS.ID = BOOKING.CLASSID JOIN CLASSLEVEL ON CLASS.CLASSLEVELID = CLASSLEVEL.ID JOIN [DAY] ON CLASS.CLASSDAY = [DAY].ID JOIN INSTRUCTOR ON CLASS.INSTRUCTORID = INSTRUCTOR.ID
WHERE [DAY].ID = (DATEPART(dw, GETUTCDATE() AT TIME ZONE \'AUS Eastern Standard Time\'))
ORDER BY CLASS.CLASSTIME ASC, INSTRUCTOR.FIRSTNAME ASC, CLASSLEVEL.CLASSLEVEL ASC';
// COUNTERS
$t = 0;
$i = 0;
//VARIABLES FOR DAY SCHEDULE
$classDay = NULL;
$classTime = NULL;
$classInstructor = NULL;
$closeClass = false;
$closeAll = false;
$queryConnector = $conn->query($dayScheduleQuery);
foreach ($queryConnector as $schedule) {
// CLASS DAY HEADER
if ($classDay != $schedule['DAY']) {
echo '<div class="grid-1">';
echo '<h1>' . $schedule['DAY'] . '</h1>';
echo '</div><!-- Day closed! -->';
$classDay = $schedule['DAY'];
}
// CLASS TIME HEADER
if ($classTime != $schedule['CLASSTIME']) {
if($classTime != $schedule['CLASSTIME'] && $t > 0) {
$closeAll = true;
goto closeAll;
}
echo '<div class="grid-12-noGutter scheduleContainer">'; //NON-CLOSED
echo '<h1>' . 'T = ' . $t . '</h1>';
echo '<div class="grid-middle-center col scheduleTimeTab">';
// FIX 3 DIGIT MILITARY TIME
if (strlen($schedule['CLASSTIME']) < 4) {
$classScheduleTime = '0' . $schedule['CLASSTIME'];
} else {
$classScheduleTime = $schedule['CLASSTIME'];
}
echo '<p>' . date('g:i A', strtotime($classScheduleTime)) . '</p>';
echo '</div>'; //CLOSE TIME TAB
echo '<div class="innerSchedule">'; // NON-CLOSED
$classTime = $schedule['CLASSTIME'];
$t += 100;
}
// INSTRUCTOR HEADER
if ($classInstructor != $schedule['INSTRUCTOR']) {
if ($classInstructor != $schedule['INSTRUCTOR'] && $i > 0) {
$closeClass = true;
goto closeClassWrapper;
}
echo '<div class="classWrapper">';
echo '<h1>' . 'I =' . $i . 'T = ' . $t . '</h1>';
echo '<div class="grid-3-middle classHeader">';
echo '<div class="col classHeaderCell' . classLevelColour($schedule['CLASSLEVEL']) . '">' . $schedule['CLASSLEVEL'] . '</div>';
echo '<div class="col classHeaderCell">' . $schedule['INSTRUCTOR'] . '</div>';
echo '<div class="col classHeaderCell">Max' . ' ' . $schedule['MAXSTUDENT'] . '</div>';
echo '</div>';
echo '<div class="grid-4-middle" id="studentHeaders">';
echo '<div class="col"><h6>Student Name</h6></div>';
echo '<div class="col"><h6>Student Birthday</h6></div>';
echo '<div class="col"><h6>Class Level</h6></div>';
echo '<div class="col"><h6>Attendance</h6></div>';
echo '</div>';
$classInstructor = $schedule['INSTRUCTOR'];
$i += 100;
}
echo '<div class="grid-4 studentRow">';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTFIRST'] . ' ' . $schedule['STUDENTLAST'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTDOB'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['CLASSLEVEL'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">--</span>';
echo '</div>';
echo '</div>';
// GOTO TAGS
closeClassWrapper: {
if ($closeClass === true) {
echo '</div>';
$closeClass = false;
$i = 0;
}
}
closeAll: {
if ($closeAll === true) {
echo '</div>';
echo '</div>';
echo '</div>';
$closeAll = false;
$t = 0;
$i = 0;
}
}
}
}
Any help would be greatly appreciated - even if it's to tell me I'm going about it the completely wrong way.
Kindest Regards
Michael Z
I wouldn't say you're going about it the completely wrong way, but a few red flags jumped out at me in your code.
The use of goto jumping is bad practice. It butchers your program flow and forces you to segregate tasks that shouldn't be kept apart. You marked the sections of code "// NON CLOSED" when there was a </div> missing, is there any purpose for that? How do you know the goto sections are reliable?
When you echo something like <div class="col">, without escaping the double-quotes (as in \" for every " character), it can be problematic. Your code can get mangled or misinterpreted, both on the PHP end or on the HTML end.
Like others have said, the use of PHP may be overkill here. Besides just sending the JSON, the rest could be handled with JavaScript.
I need some help with solving duplicating problem. To deal:
I have 2 filed custom meta
It displays this way :
Only 2 image placed, but it duplicate <li>.
First and third <li> is only video, second and fourth works fine, looks like this :
foreach($slider_xml->childNodes as $slider){
$test_test = get_post_meta(9,'test_1', false);
foreach($test_test as $test_test){
echo '<li class="img-vid-slide">';
echo '<iframe src="https://www.youtube.com/embed/'. $test_test . '" frameborder="0" allowfullscreen></iframe>';
}
echo '<div class="img-slide" >';
if($link_type == 'Lightbox'){
$image_full_url = wp_get_attachment_image_src(find_xml_value($slider, 'image'), 'full');
echo '<a href="' . $image_full_url[0] . '" data-rel="prettyPhoto[flexgal]" title="" >';
}else if($link_type != 'No Link'){
echo '<a href="' . $link . '" >';
}
echo '<img class="'. $i .'" src="' . $image_url[0] . '" alt="' . $alt_text . '" />';
echo '</div>';
if( !empty($title) ){
echo '<div class="flex-caption gdl-slider-caption">';
echo '<div class="gdl-slider-title">' . $title . '</div>';
echo '<div class="slider-title-bar"></div>';
echo $caption;
echo '</div>'; // flex-caption
}
if($link_type != 'No Link'){
echo '</a>';
}
echo '</li>';
}
I find solution.
Filed custom fields: prntscr.com/7oqqvt
I named them like "name_1","name_2"..."name_4".
$i is equal of last nubmer in custom field.
Result on screen: prntscr.com/7oqsaw
$i = 1;
while ($i <= 3):
foreach( $slider_xml->childNodes as $slider ){
// ======= SAME AS FIRST ====== //
$test_test = get_post_meta(9,'test_'. $i .'', true);
echo '<iframe src="https://www.youtube.com/embed/'. $test_test . '" frameborder="0" allowfullscreen></iframe>';
echo '<div class="img-slide" >';
if($link_type == 'Lightbox'){
// ======= SAME AS FIRST ====== //
}
echo '</li>';
$i++;
}
endwhile;
Works fine for me, do what i searching for!
Thanks, Greg, for a little hint, but i go for "while" instead of "for"! Good luck
Don't use the a foreach inside a foreach loop. It a function problem.
Use the alternative "for" loop instead of the double foreach.
Ok, So Im creating a while loop for multiple accordions in php. I marked up some php code that ALMOST works. The problem I am having is that I had to nest five different IF statements in a while loop for the five different accordions. The If statements contain the content to be in the accordion. The content is a list of songs in a particular album. What I need to happen is for the If statement containing the content for one accordion to break, but still continue with the original while statement and do this for each accordion. Here is my PHP Code.
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo '<div class="col-small-6 col-med-6 col-lg-4 albumContainer">';
echo '<img src=' . $row['Album_Art'] . 'alt="">';
echo '<div class="panel-group" id="accordion">';
echo '<div class="panel panel-default">';
echo '<div class="panel-heading">';
echo '<h2 class="panel-title"><a data-toggle="collapse" data-parent="#accordion" href=' . $row['direction'] . '>' . $row['Title'] . '</a></h2></div><div id=' . $row['destination'] . ' class="panel-collapse collapse"><div class="panel-body"> <ol>';
if($result1)
{
while ($row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC))
{
echo '<li>' . $row1['Name'] . '</li>';
};
};
if($result2)
{
while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC))
{
echo '<li>' . $row2['Name'] . '</li>';
}
};
if($result3)
{
while($row3 = mysqli_fetch_array($result3, MYSQLI_ASSOC))
{
echo '<li>' . $row3['Name'] . '</li>';
}
};
if($result4)
{
while($row4 = mysqli_fetch_array($result4, MYSQLI_ASSOC))
{
echo '<li>' . $row4['Name'] . '</li>';
}
};
if($result5)
{
while($row5 = mysqli_fetch_array($result5, MYSQLI_ASSOC))
{
echo '<li>' . $row5['Name'] . '</li>';
}
};
if($result6)
{
while($row6 = mysqli_fetch_array($result6, MYSQLI_ASSOC))
{
echo '<li>' . $row6['Name'] . '</li>';
}
};
echo '</ol>';
echo '<h3>available at:</h3><a href=' . $row['Location'] . '>iTunes</a>
<a href=' . $row['Location2'] . '>Amazon</a>
<a href=' . $row['Location3'] . '>United Interests</a></div>';
echo '</div></div></div></div>';
}
mysqli_free_result ($result);
}
else
{
echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';
echo '<p>' . mysqli_error($dbcon) . '<br><br />Query: ' . $q . '</p>';
}
mysqli_close($dbcon);
?>
Any insights on how to make this work for me would be greatly appreciated. I cant use Jquery for the accordion because of how the code was previously structured.
use continue http://php.net/manual/en/control-structures.continue.php
continue is used within looping structures to skip the rest of the
current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration.
Note: Note that in PHP the switch statement is considered a looping
structure for the purposes of continue.
also, you should probably use a switch instrad of multiple if conditions
Here is what i got:
$pagecount=0;
while($row = $result->fetch_assoc()){
echo '<div style="background-image:url(images/paper.jpg);">';
while ($pagecount < 3) {
while($row = $result->fetch_assoc()){
echo '<div class="content"><div class="name">' . $row['victim'] . '</div><div class="cod">' . $row['cod'] . $pagecount . '</div></div>';
$pagecount++;
}
}
$pagecount=0;
echo '</div>';
}
The problem is that when this is run, it will print out $victim, $cod and then $pagecount. I never want pagecount to be higher than 3, so i put in the while statement, so when it hits 3 it should exit out of the loop, and then pagecount should go back to 0 and then start increasing again. however when this is run, pagecount just keeps on getting higher, and doesn't hit 3 and then go back to 0. Can anyone help?? Is there something wrong with my condition or loop or something?
Also just on the side, can anyone tell me instead of using the first $row = $result->fetch_assoc() is there something i can use to check if the result wont be empty, because at the moment, it will skip the first entry in the mysql db.
Cheers guys!
EDIT: Tested everyones solution so far, and they all worked for me.
It just shows how there are many different ways you can do one thing!
Thank you everyone, you were all very, very helpful. Much appreciated. :)
What i ended up going was completley removing the whole while statement from the inner loop.
However because of the first $row = $result->fetch_assoc() there first DB entry is still getting skipped.
Any way around this?
Try this :
$pagecount=0;
while($row = $result->fetch_assoc()){
echo '<div style="background-image:url(images/paper.jpg);">';
while($pagecount < 3 && $row = $result->fetch_assoc()){
echo '<div class="content"><div class="name">' . $row['victim'] . '</div><div class="cod">' . $row['cod'] . $pagecount . '</div></div>';
$pagecount++;
}
$pagecount=0;
echo '</div>';
}
Using $row = $result->fetch_assoc() inside a loop using $row = $result->fetch_assoc() will make the pointer of your result to go too forward.
I advice you to store all the objects in an array before performing your loops.
while ($pagecount < 3) {
while($row = $result->fetch_assoc()){
echo '<div class="content"><div class="name">' . $row['victim'] . '</div><div class="cod">' . $row['cod'] . $pagecount . '</div></div>';
$pagecount++;
}
}
Your inner while will keep looping as long as it can fetch_assoc, because you don't check the pagecount.
Move the condition to the inner while:
while($pagecount < 3 && $row = $result->fetch_assoc()){
echo '<div class="content"><div class="name">' . $row['victim'] . '</div><div class="cod">' . $row['cod'] . $pagecount . '</div></div>';
$pagecount++;
}
$pagecount++;
should be moved out of the inner loop, i.e.
while($row = $result->fetch_assoc()){
echo '<div class="content"><div class="name">' . $row['victim'] . '</div><div class="cod">' . $row['cod'] . $pagecount . '</div></div>';
//moved 1 level: $pagecount++;
}
$pagecount++;
}
indenting your code might have helped :)