i am trying to get my data from the database and wrap it with html tags. here is the working code so far:
function homethumb(){ $this->count; $i = 0;
while($row = mysqli_fetch_object($this->result))
{
$this->count++; $i++;
if($i == 1){echo '<div class="gal1">';}
echo ' <div class="gal"><img src="img/' . $row->thumb2 . '.jpg"></div>';
if($i == 2){
echo '</div> <!-- gal1 -->';
$i=0;
}
}
}
Here I am getting everything from the database (Select * from portfolio), but in the portfolio I have, websites, demos and graphics; so I wanted to get only the data where category = "web" from the above code, so I tried this:
function homethumb(){ $this->count; $i = 0;
while($row = mysqli_fetch_object($this->result))
{
if($row->category = "web"){
$this->count++; $i++;
if($i == 1){echo '<div class="gal1">';}
echo ' <div class="gal"><img src="img/' . $row->thumb2 . '.jpg"></div>';
if($i == 2){
echo '</div> <!-- gal1 -->';
$i=0;
}
}
}
}
now the nested if statements do not generate the divs I need, how can I get this working
thanks for your help
I can't see your SQL based on your question, but you could just modify your SELECT query to include WHERE category="web"
This way, you're only selecting the rows you need, instead of looping over every row in that table.
Additionally, it appears that you're using assignment = instead of comparison == for your if statement.
Do you just need to have == instead of =?
if($row->category == "web"){
But it would be best to restrict the query to the results you need at the database level, unless you need the other rows for some reason.
1)You missed an equal sign:
if($row->category = "web") => if($row->category == "web")
Or better yet
if($row->category === "web")
2)If you want to only get fields with a specific category field, you can simply change your query:
[rest of your query] WHERE category="web"
OK, it should go like this, assuming the fields are sorted as follows
ID, category, website, thumb2, demo, graphics
function homethumb(){ $this->count; $i = 0;
while($row = mysqli_fetch_object($this->result))
{
if($row[1] == "web"){
$this->count++; $i++;
if($i == 1){echo '<div class="gal1">';}
echo ' <div class="gal"><img src="img/' . $row[3] . '.jpg"></div>';
if($i == 2){
echo '</div> <!-- gal1 -->';
$i=0;
}
}
}
}
and there is no need for the nested if, you can just use it in one line as follows:
if($row[1] = "web")
{
echo '<div class="gal1">';
echo ' <div class="gal"><img src="img/' . $row[3] . '.jpg"></div>';
echo '</div> <!-- gal1 -->';
}
1) Change your query to contain a WHERE category="web" clause
2) You have an assignment operator in your if clause (=), when you need an equality operator (==)
Related
I need to divided all data into 4 columns. i have used this method but its not coming column property
$stmt1 = $db->prepare($sql1);
$stmt5 = $db->prepare($sql1);
$stmt5->execute();
$rowcount = $stmt5->rowCount();
$pages = ceil($rowcount / 4);
$tempcount = 1;
if ($stmt1->execute(array())) {
while ($row = $stmt1->fetch()) {
?>
<?php if ($tempcount == $pages) { ?>
<div class="column">
<div class="ui bulleted list">
<?php } ?>
<?php
if ($tempcount == $pages) {
$pages = $pages + $pages; ?>
</div>
</div>
<?php }
$tempcount++;
}
} ?>
how i can get this columns after getting count of data i have and add those divs in between.
for an Example 20 data rows 20/4 = 5 after each 5 data, i need start and end to be added
<div class="column">
<div class="ui bulleted list">
</div>
</div>
<div class="column">
<div class="ui bulleted list">
</div>
</div>
// And so on
result will be like this
thank you very much
Here's a proper code with comments
$tempcount = 0;
$pages = ceil($rowcount / 4);
while ($row = $stmt1->fetch()) {
// if result of % (Modulo) is zero - you need to start new column
if ($tempcount % $pages == 0) {?>
<div class="column">
<div class="ui bulleted list">
<?php
}?>
ITEM
<?php
// if result of % (Modulo) is (pages - 1) - you need to close previous column
if ($tempcount % $pages == ($pages - 1)) {?>
</div>
</div>
<?php
}
$tempcount++;
}
// check if you have to close previous column
// because it was not closed in a while loop
if (0 < $rowcount) {
if ($tempcount % $pages != 0) {?>
</div>
</div>
<?php
}
}
Whilst the modulo approach mentioned above will help in these situations, I often find that writing your loops from a different perspective can help in sorting out the situation, and making things more readable.
Rather than looping through every row, and then inserting the columns where you think they need to be. Instead loop every item, but in a controlled count, wrapped by the columns.
I've switched the code to using echo just due to personal preference, you can still use php-breakouts instead if preferred.
Please note this is untested example code, just to illustrate the point:
<?php
$stmt1 = $db->prepare($sql1);
$stmt5 = $db->prepare($sql1);
$stmt5->execute();
$rowcount = $stmt5->rowCount();
$pages = ceil($rowcount / 4);
if ($rowcount) {
$stmt1->execute(array());
do {
$group = '';
$group .= '<div class="column">';
$group .= '<div class="ui bulleted list">';
for ( $i=0; $i<$pages; $i++ ) {
$row = $stmt1->fetch(); if ( !$row ) { break; }
// presumably something would be done with $row here
$group .= '';
}
$group .= '</div>';
$group .= '</div>';
echo $group;
} while ( $row );
}
% modulo will help you PHP operators. While you fetch, use it to create your divider. If using div and if needed, I usually add a tiny div with clear: both to make sure it breaks the line after the 4/8/12... results.
$cell++;
$jumpline = ($cell % 4) ? "" : "<div class=\"spacer\"></div><br />";
$endit = ($cell % 4) ? "" : "</div>";
Just beginning PHP to bear with me.
Results I'm trying to achiever:
I have a table of YouTube URL's and MetaData.
Trying to build this:
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
Two videos per slide, then I'm going to paginate through results using Deck.js.
I suspect I'm going about this completely the wrong way, not that experienced at programmin g logic;
while($data = mysql_fetch_array($result)) {
for ($counter = 1; $counter<=2; $counter++) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
/* If Video 1, increment counter for 2nd video */
if ($counter == 1) {
$counter++;
}
/* If Video 2, close div and reset counter */
else if ($counter == 2) {
echo "</div>";
$counter = 1;
}
/* If error break out */
else {
echo "</div>";
break;
}
}
}
Basically trying to nest loops to keep track of how many videos per div and start a new one when a div has two.
I've tried a few different ways, this being the latest. Results in:
<div class="slide">
<iframe></iframe>
<div class="slide>
<iframe></iframe>
Hit the blank wall now, not sure what to try next. Willing to use/learn any method to accomplish the results, just not sure where to go at this point.
Cheers.
You could remove the second loop all together using the % operator (modulus). The idea is that a % b === 0 then the number a was evenly divisible by b. Using this, you can easily check for even or odd or every Nth row.
$k = 1;
echo "<div class=\"slide\">";
while($data = mysql_fetch_array($result)) { // you should really change to mysqli or PDO
if($k % 3 === 0){
echo "</div>";
echo "<div class=\"slide\">";
}
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
$k++;
}
echo "</div>";
Put the echo <div> before the for loop (still inside the while loop) and the </div> after the for loop
In your while loop you're retrieving just one row, but then you're iterating over it twice with a nested loop. Do away with the inner loop and just use a flip-flop variable to track left and right. I think this will do what you want:
$left=true; // track whether we're emitting HTML for left or right video
while($data = mysql_fetch_array($result)) {
if ($left) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
}
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
if (!$left) {
echo "</div>";
}
$left = !$left; // invert $left to indicate we're emitting the right iFrame
}
// end of loop. If we had an odd number of
// videos, tidy up the HTML
if (!$left) {
echo "</div>";
}
PHPFiddle
<?php
$x = 10;
$counter = 0;
while($x > 0)
{
if($counter != 0 && $counter % 2 == 0)
{
echo "ENDOFSLIDE</br>";
}
if($counter == 0 || $counter % 2 == 0)
{
echo "SLIDE</br>";
}
echo "iframe => $x </br>";
$x--;
$counter++;
}
echo "ENDOFSLIDE";
?>
It won't work because the for loop is inside the fetch loop for the SQL data. The second iteration of the for loop does not have a new SQL row. A better solution would be to capture the common column that identifies the two videos (the title) and generate a new div whenever that value changes. Try something like this, which will work for any number of SQL rows with the same title. This will also give proper results if the SQL query returns no rows and will handle the potential of a title with only one URL - which could get ugly if you merely flip-flop and end up with URLs on the wrong title. Of course, as in your current solution, your SQL query must ORDER BY VIDEO_TITLE so the rows are adjacent. I didn't run it, but should be close.
$lastTitle = "";
$n = 0; //count SQL rows processed
while($data = mysql_fetch_array($result)) {
// See if the title changed from last
if( $data['VIDEO_TITLE'] != $lastTitle ) {
// if we processed any rows, must end the current div before starting a new one
if( $n > 0 )
echo "</div>";
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
//save the title as last title
$lastTitle = $data['VIDEO_TITLE'];
}
$n++; //count the SQL row
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
}
if( $n > 0 )
echo "</div>";
I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});
Please forgive the extreme-beginner style of coding. I'm working with PHP and JSON strings from an API for the first time.
What I'm trying to do here, which obviously doesn't work if you look through it, is print out multiple movie results that the user is searching for. This is a search results page - with a movie poster and some key details next to each item.
One of the things I want next to each result is a list of the first 5 actors listed in the movie, as "Starring" and then any directors listed in the movie as "Director".
The problem is no doubt the fact that I've nested foreach statements. But I don't know any other way of doing this.
Please please the simplest answer would be the best for me. I don't mind if it's bad practice, just whatever solves it quickest would be perfect!
Here's the code:
// Check if there were any results
if ($films_result == '["Nothing found."]' || $films_result == null) {
}
else {
// Loop through each film returned
foreach ($films as $film) {
// Set default poster image to use if film doesn't have one
$backdrop_url = 'images/placeholder-film.gif';
// Loop through each poster for current film
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'thumb') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<img src="' . $backdrop_url . '" alt="' . strtolower($film->name) . '" />
<div class="view-films-film-snippet">
<h2>' . strtolower($film->name) . '</h2>
<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />
<h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Actor') {
echo '' . $cast->name . ' ';
$num_actors++;
if ($num_actors == 5)
break;
}
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Director') {
echo '' . $cast->name . ' ';
}
}
echo ' </p>
</div>
</div>';
// End films
}
}
An example of the result would be this:
with line 120 being foreach ($films[0]->cast as $cast) { and line 131 being foreach ($films[0]->cast as $cast) {
Why are you using $films[0] when you're in a foreach ($films as $film)? You should be using $film->cast right? And you should dump $film at the start of your loop with var_dump and inspect it - make sure $cast is an array and is populated. If it's not, work back from there.
I´m fetching my database for images to create a gallery. Every row appear inside a <li>. My question is, is it possible, that the first <li> have a class (for example, "visible"), and all the other <li> have a class named "hidden". So the first $row would have a different class than the following...
Hope I made myself clear!
Thanks
Well thats easy! Just track the row number, if it is the first row then echo out class="visible" else class='hidden"
It can be done more shortlier like this:
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="' . (($i == 1) ? 'visible' : 'hidden') . '">';
$i++;
}
How about something like
$visible = true;
while(...) {
if($visible) {
echo "<li class='visible'>";
else {
echo "<li class='hidden'>";
}
$visible = false; // Every loop sets it to false, which after the first one will make no difference.
}