PHP/MySQL 2 'while' statements from 1 mysql query? - php

I was wondering if it's possible to have 2 'while' statements using the same 'mysql_query'?
I'm using a jquery thumb gallery with the results pulled in from a database. The gallery requires that the images are grouped together in an unordered list, with the text/overlayed content grouped together in hidden divs which need to be separate from the unordered list. The reason for doing this is because there are many potential results that could go in here and bringing them in randomly seems to make sense.
Here's the code I'm currently using: Any help greatly appreciated, S.
<div id="banner-wrap">
<div id="banner" class="gallery">
<ul class="galleryBar">
<?php
$homeB=mysql_query("select * from istable where fpGallery = '1' ORDER BY RAND() LIMIT 0, 5");
while($homeG=mysql_fetch_array($homeB)) {
$linkcode = $homeG['title'];
$linkcode = str_replace(" ","",$linkcode);
echo '
<li>
<a href="'.$wwwUrl.'images/'.$homeG['image'].'" rel="'.$linkcode.'">
<img src="'.$wwwUrl.'images/tn/'.$homeG['image'].'" width="75" height="55" alt="'.$homeG['title'].'" />
</a>
</li>
';
}
echo '</ul>';
echo '</div>';
while($homeGal=mysql_fetch_array($homeB)) {
echo '
<div id="'.$linkcode.'" class="overlay">
<h3>'.$homeGal['title'].'</h3>
<h4>'.$homeGal['location'].'</h4>
</div>
';
}
?>
</div>

Try to reset the iterator of the query result by calling mysql_data_seek($homeB, 0) between the two while loops.

WHERE `column1` = 'value1' AND `column2` = 'value2'

Your unindented code is hard to follow but it appears that you're asking whether mysql_fetch_array() starts again when it reaches the last row. The answer to that is no.
Can you rewind the result set? In theory, you can (find mysql_data_seek() in the manual). But there's no need to make it so complicate: just read data once, store it into an array and loop the array as many times as you need.

Related

Sort Gallery by value of specific Array Key, then display value of another key [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 months ago.
I have a multidimensional array that is used to pull images and data into the page. The page will also have a sort by system which will display only the array items that have a certain tag (currently tagging yes or no with 0 and 1) I am using an if statement to decide whether the page displays the default (all of the photos) or the sorted array. The default works fine on its own, but im trying to get the sorted to display. When i include the html/php for displaying the images, instead of "echo $mImage['img_caption'];" (Which is a stand in, im just testing if i can even get the statement to display the items. Instead of the full caption string, it displays the first character of every value of every key.) i get errors akin to "unexpected "{" or "<" and the page wont load. Ive basically had to teach myself php over the course of three days, so im sure im missing something easy. Ill include an example of the array, the php for the sort, and the section that works to display the entire array.
Here is my arrays
$arrImages[] =
[
'img_sm'=>'exampleple.jpg',
'img_lg'=>'example2.thumb.jpg',
'img_caption'=>'multifamily',
'img_description'=>'example',
'img_path' => 'img/getest',
'img_type'=>'getest',
'MultiFamily'=>1,
];
$arrImages[] =
[
'img_sm'=>'example.jpg',
'img_lg'=>'example.thumb.jpg',
'img_caption'=>'notmultifamily',
'img_description'=>'example786',
'img_path' => 'img/getest',
'img_type'=>'getest',
'MultiFamily'=> 0,
];
And here is the if statement
<?php
$sorted = 1;
//If the viewer is sorting, check what they are sorting by and then sort by that before pushing the page to change display.
if ($sorted = 1){//start if sorted statement
$MultiFamilySorted = 1; //replace this with a function that checks all checkboxes to see if they are sorted by that or not. This is simulating that the viewer is sorting to see only multifamily homes.
foreach($arrImages as $sortedImages)://Start sort loop
if ($sortedImages['MultiFamily'] = 1){//start display sorted
foreach($sortedImages as $mImage): //start display loop
echo $mImage['img_caption'];//i am just using this to test if it will display
endforeach;
}//end display sorted
endforeach;
}//end if sorted statement
?>
This is the section for my default display
<div class="ImageDisplayTestBox">
<?php
foreach($arrImages as $mImage): //loop through the image array
?>
<div class="masonry-item no-default-style col-sm-3">
<a href="<?php echo $mImage['img_path'] . '/' . $mImage['img_lg']; ?>">
<span class="thumb-info thumb-info-centered-info thumb-info-no-borders">
<span class="thumb-info-wrapper">
<img src="<?php echo $mImage['img_path'] . '/' . $mImage['img_sm']; ?>" class="img-fluid" alt="">
<span class="thumb-info-title">
<span class="thumb-info-inner"><?php echo $mImage['img_caption']; ?></span>
<span class="thumb-info-type"><?php echo $mImage['img_type']; ?></span>
</span>
<span class="thumb-info-action">
<span class="thumb-info-action-icon"><i class="fas fa-plus"></i></span>
</span>
</span>
</span>
</a>
</div>
<?php endforeach; //end loop ?>
</div>
Thanks!
I did not check you code for the syntax error you mentioned, but there is a simpler way of doing this:
<?php
if ($sorted == 1){
$arrImages = array_filter($arrImages, function($image){
return $image['MultiFamily'] == 0;
});
}
?>
You can use this instead of your sorting code.
This executes the sorting function for each array member. If the function returns true it will pass it to the the sorted array. If it is false it will skip it.
The documentation of array_filter is here: https://www.php.net/manual/de/function.array-filter.php

Automatic generation of <div> tag into Html webpage

i have these lines of code:
<div class="signals">
<ul>
<li>First Signal</li>
<li>Second Signal</li>
<li>Third Signal</li>
</ul>
</div>
<div id="signal1" style="display:none;">
<p style="color:#fff">First comment for #signal1 id - it will open in a fancybox -.</p>
<div id="signal2" style="display:none;">
<p style="color:#fff">Second comment for #signal2 id - it will open in a fancybox -.</p>
</div>
<div id="signal3" style="display:none;">
<p style="color:#fff">Third comment for #signal3 id - it will open in a fancybox -.</p>
</div>
Here it is the jsfiddle code: JsFiddle
Right now when i want to show different comments, i open my html file and edit the "id #signal , adding more id (or deleting them) when i need it.
The problems is: the signals can be more than the three that are showed up, or even less.
So my question is:
There is a way to generate automatically the divs that i need in a second sheet, where i will insert the comment and all the id's? (a sort of backend)
For example: if one day i need just 2 signals, i will create the #signal1 and #signal2 div, i'll insert the comments and save the secondary sheet.
When i do that, the primary sheet with the html stuff, will show 2 "li" lines:
First Signal
Second Signal
and when i click on of them, the fancybox will open and show the comment, just as the code into the jsfiddle.
I don't know much of php, but there is a way i can do that using it? Or there is a better way?
Hope i can learn from your help.
It seems that you need PHP foreach loop.
You can write the comments in a PHP array, and read them using PHP foreach.
Here is the sample code:
<?php
$commentsLabels = array('First Signal','Second Signal');
$commentsTexts = array('First comment for #signal1 id - it will open in a fancybox.','Second comment for #signal2 id - it will open in a fancybox.');
//You could use a 2D array to store both comments Labels and comments Texts in one array, but since you are new to PHP, I put them in 2 different arrays to make it easy.
//You can add more comments texts/labels to the arrays in double/single quotes separated with ','
//For now, the arrays are filled manually. in future, you can add a DB to store comments and fetch the values from there.
$counter = 0;
//we need a counter to make the comment ids dynamic
?>
<!--GENERATING LABELS-->
<div class="signals">
<ul>
<?php
foreach ($commentsLabels as $commentLabel) { //loop starts
$counter++; //increasing $counter by 1, for each iteration
//We have to add HTML tags outside the php code block.
?>
<li><?php echo $commentLabel; ?></li>
<?php
} //loop ends
?>
</ul>
</div>
<!--GENERATING POPUPS-->
<?php
$counter = 0; //reset counter
foreach ($commentsTexts as $commentText) { //loop starts
$counter++;
?>
<div id="signal<?php echo $counter; ?>" style="display:none;"><p style="color:#fff"><?php echo $commentText; ?></p></div>
<?php
} //loop ends
?>
I hope this helps you start. :-)

Easiest way to Format MySQL Data to Next Column in PHP

I have my data being output to a span currently... this is how it looks:
Now, when i remove the span and place a div there i am given this output:
This is desired, but I want to set a height to my page and have the data show up in as little as 3 columns. How would I do this? I have searched everywhere online but can't seem to find anything that shows a solution.
I did read that some use javascript for the format but i am still clueless on even this option.
My desired output would look like this:
If you know how many items you want in a column then you can seperate them out into individual divs and then float those divs to the left to get them to be next to each other.
<div style='float:left'>
//Items go here
</div>
<div style='float:left'>
//Items go here
</div>
etc.
If you figure out how many items your query returned, say using mysql_num_rows() and divide by 3 you can tell how many to put in each column.
Also be sure to clear the floats afterwards, so like this:
<div style="clear:both"></div>
Sometimes this is necessary as there will be random issues if this is not put there.
What you are describing can be solved with styling only. You have several divs that must be displayed in columns. The easiest way is floating them to the left, and setting the width for 1/3 of the parent. If you want 4 columns, set the with to 1/4 of the parent, and so on.
<div class='sqlResult' style="float:left;width:33%;">
<a href='#'>$key</a>
</div>
Also as other answers mentioned, don't use duplicated ids. Always use classes. If you need to target each div individually, give it a unique id, such as "category_1", "category_2", and so on.
This should work
<table><tr>
<?php $count=0; $total=mysqli_stmt_num_rows($sql)-1; $idxcount=0; $limit=10; while($row = mysqli_fetch_array($sql)): $key = $row['Keyword_Name']; ?>
<?php if($count == 0){ echo '<td>';} ?>
<span>
<?php echo $key; ?>
</span>
<?php if($total == $idxcount): ?>
</td>
<?php elseif($count == $limit): ?>
</td>
<?php $count=0; else: $count++; ?>
<?php endif; $idxcount++; ?>
<?php endwhile; ?>
</tr></table>

Iterate through two arrays, looping one continuously until the other is finished (i.e. Assign colors to menu navigation items)

O.K. Can't quite get any reference to something similar. I have two arrays, one sets my menu navigation items:
$nav_items = array('item1_link'=>'item1_displayname',
'item2_link'=>'item2_displayname',
'item3_link'=>'item3_displayname',
. . .
Then, I have my second array, which sets a number of possible colors:
$colors = array('red'=>'#f00',
'green'=>'#090',
'yellow'=>'fc0',
. . .
The idea is to merge these two so that the result will be:
<a class="red" href="item1_link">item1_displayname</a>
<a class="green" href="item2_link">item2_displayname</a>
<a class="yellow" href="item3_link">item3_displayname</a>
The thing is: imagine I have 10 menu items and I decide on 7 different colors. The idea is that (this is where I'm stuck) a main loop will iterate through the 10 menu items, assigning to each one of the color items from a second loop, which should cycle one time and then a second time (and a third, etc., if necessary) until all items from group 1 have been exhausted.
Perhaps an example of what I want to end up with will be more helpful:
<a class="red" href="item1_link">item1_displayname</a>
<a class="green" href="item2_link">item2_displayname</a>
<a class="yellow" href="item3_link">item3_displayname</a>
<a class="blue" href="item4_link">item4_displayname</a>
<a class="orange" href="item5_link">item5_displayname</a>
<a class="purple" href="item6_link">item6_displayname</a>
<a class="gray" href="item7_link">item7_displayname</a>
<a class="red" href="item8_link">item8_displayname</a> <!--Notice how colors restart here-->
<a class="green" href="item9_link">item9_displayname</a>
<a class="yellow" href="item10_link">item10_displayname</a>
So, PHP-code-wise, what I've got up to now is the following:
<?php
reset($nav_items);
reset($colors);
while ((list($nav_link, $nav_name) = each($nav_items))) {
list($color_name) = each($colors);
?>
<li><a class="<?php echo $color_name ?>" href="<?php echo $nav_link ?>"><?php echo $nav_name ?></a></li>
<?php
}
?>
Which is not bad, but only goes once through color array and then repeats the last color for the remaining menu navigation items.
So, how do I get the color array to restart once its iteration is finished (and the nav_item iteration is not)??
Any help on the matter will be MUCH appreciated!
P.S. I also tried this as an Iterator but couldn't quite get it to work. Perhaps that is the best response after all, but still I couldn't get the colors array to loop back in order to complete the nav_items array cycle.
if (current($colors) === false) reset($colors);
You might want to consider using the modulo operator:
$number_of_colors = count($colors);
$loop_count = 0;
foreach($nav_items as $nav_link => $nav_name) {
$use_color = $colors[$loop_count % $number_of_colors];
echo "<li><a class='{$use_color}' href='{$nav_link}'>{$nav_name}</a></li>\n";
$loop_count++;
}
Edit: Oups, sorry, didn't realize you have the names of your colors you want to use as CSS class as keys in your array... If you must have it organized this way, you could do this:
$color_classes = array_keys($colors);
and then use $color_classes instead of $colors in the snippet I provided above.

CSS Class on end MySQL row

I am having trouble creating a solution that will target the end row of a MySQL query. Currently I have a foreach function that works through the query and displays each one as a div with the information inside:
<?php $residents = Resident::find_all();
foreach($residents as $resident): ?>
<div class="submenu">
<p class="menuitem submenuheader"><?php echo $resident->name; ?></p>
<img src="images/<?php echo $resident->image_path(); ?>" width="250" class="image" />
<p><?php echo $resident->info; ?></p>
</div>
.submenu currently has a bottom border. I need to remove this on the last row returned. I have looked at DESC LIMIT 1, however this requires another MySQL query and could make things very messy...
Addd this to your CSS:
.submenu:last-child { border-bottom: 0; }
Note: this is not supported by IE < 9.
You could switch to putting the border on the top of the element, and use the :first-child pseudo selector in CSS to remove it.
http://reference.sitepoint.com/css/pseudoclass-firstchild
The :last-child selector would be nice, but it's not supported in IE before version 9, so it's not a good idea to use it if you want compatibility.
If you separate your HTML and PHP a little this is easily achieved:
<?php
function echoBlock($resident,$pClass="menuitem submenuheader") {
echo "<div class=\"submenu\">\n<p class=\"$pClass\">\n";
echo $resident->name;
echo "</p>\n<img src=\"images/";
echo $resident->image_path();
echo "\" width=\"250\" class=\"image\" />\n<p>";
echo $resident->info;
echo "</p>\n</div>\n\n";
}
$residents = Resident::find_all();
$last=count($residents)-1;//2 element array last pos is 1
for ($i=0;$i<$last;$i++) {
echoBlock($residents[$i]);
}
echoBlock($residents[$last],"menuitem");
?>
echoBlock (which could easily be a method on a class) requires the calling code to know about the classes it uses, which isn't really separating intent but it does prevent the need for an if branch on every loop. That being said it would be less efficient but perhaps more usable to set it up as:
function echoBlock($resident,$isLast=false) {
$pClass="menuitem".($isLast?"":" submenuheader");
//...
Which then doesn't need the caller to know anything about what echoBlock does.
You could try and pop the array using array_pop(), to get the last value out of the array and then inputing it using the special class after the foreach loop.
What about
Instead of echo'ing each line one by one, create one big string in PHP, search for the last entry of "submenu" and change the class.

Categories