I am creating a search, and what I want is when the user searches they will be able to see a number of different attractions appear. At the minute when I search the data appears in a long list.
else {
while ($row = mysqli_fetch_array($result)) {
$attraction_name = $row['attraction_name'];
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$image = "<img src='{$row['image']}' height='100' width='100'>";
$output .= '<div>'.$attraction_name.' '.$lat.' '.$long.' '.$cost.' '.$image.'</div>';
}
}
I have added a simple html format which looks like the following
<div class="col-md-4">
<div class="thumbnail">
<?php print ("$output");?>
</div>
However the html appears all the time and I don't want this. What I would like is to create a search and then when the search results are returned they will appear in the html divs. Does anyone know how to do this? Thanks in advance.
You can wrap HTML in PHP logic like so:
<?php
if ($hasResults)
{ ?>
<div class="col-md-4">
<div class="thumbnail">
<?php print ("$output");?>
</div>
<?php }
?>
Related
For parsing a list of articles, i have this code to parse all the articles:
while($article = $articles->fetch())
{
$date = strtotime($article['createdAt']);
$formatted_date = date("F Y",$date);
?>
<br />
<div class="news-content">
<div class="news-image">
<?php echo $article['title']; ?>
</div>
<div class="news-article">
<h3>
<span><?php $date = strtotime($article['createdAt']); echo /*date("F j",$date);*/ strftime('%e %B',$date) ?></span>
<br />
<?php echo $article['title']; ?>
</h3>
</div>
</div>
<?php
} //end while loop
?>
What i want to achieve: only the first 5 <div class="news-content">...</div> should be shown.
I know i have to do something with a for loop
but i do not know exactly how to use the for loop for this situation...
Can someone help me with that?
There are a lot of different ways to limit a loop. One possibility is to use a for loop instead of a while loop. for is often a good option if you want something to happen a specific number of times. Adding something else like fetch into the continuation condition will mean it happens up to a specific number of times.
for ($i = 0; $i < 5 && $article = $articles->fetch(); $i++) {
// output article
}
I am displaying information in a card-based layout, but if any title in the card is longer than 41 characters, it doesn't fit into the card.
I thought about using [wordwrap], but all that would do is cause the one specific title to wrap and change the height of that card, affecting the layout of the other cards.
This is the PHP I use to print my results for pagination purposes, so it only prints 9 things at a time.
<div class="row">
<?php
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p><? echo $row["title"]; ?></p>
<p>Category: <? echo $row["category"]; ?></p>
</div>
</div>
</div>
<?php
};
?>
</div>
How would I go about line breaking every title if even one title is detected as longer than 41 characters?
EDIT: This is the solution I created:
$titlebreak = $row["title"];
if (strlen($titlebreak) >= 40)
{
$titlebreak2 = wordwrap($titlebreak, 39, "</p><p>");
}
else
{
$titlebreak2 = $row["title"] . "<p> </p>\n";
}
I've included 3 possible solutions below - adding manual line breaks as you asked about in your question; a basic but unsatisfactory CSS option and a jQuery solution which in this case is the one I would suggest as the most flexible.
Although a CSS-only solution is usually the preferred way of fixing a layout issue, when it comes to equal heights of elements there isn't a clear-cut way to do it and often a jQuery solution like the one below is required.
Manual line-break - as requested in your question
Instead of doing an additional SQL query as mentioned, you can easily do it in the PHP in 2 different ways:
(a) loop through the rows before displaying them to calculate the title lengths, then loop again to display with/without the line break
or
(b) if you really down't want to loop twice, you could include the line break regardless of length as you loop once, but also calculate the line length in that loop. Then hide the line break using CSS if its not required
(a) 2 loops: Calculate length to determine whether to add the line break or not:
<?php
$maxchars = 41;
$cards = array();
$bLongTitle = false;
while ($row = mysql_fetch_assoc($rs_result)) {
// save detaisl to $cards array
$cards[$row["title"]] = $row["category"];
// check title lengths until we find one over 41 - no need to check any more after that
if (!$bLongTitle && strlen($row["title"])) > $maxchars)
$bLongTitle = true;
}
?>
<div class="row">
<?php
foreach ($cards as $title => $category) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p><?
// if there were any long title, wrap them all text
if ($bLongTitle)
$title = wordwrap($title, $maxchars, "<br />\n");
echo $title;
?></p>
<p>Category: <? echo $category; ?></p>
</div>
</div>
</div>
<?php
}
?>
</div>
(b) 1 loop: Always display line break, and hide it if not required
<div class="row">
<?php
$bLongTitle = false;
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p class="cardTitle"><? echo wordwrap($title, $maxchars, "<br />\n"); ?></p>
<p>Category: <? echo $row["category"]; ?></p>
<?php
// check title lengths until we find one over 41 - no need to check any more after that
if (!$bLongTitle && strlen($row["title"])) > $maxchars)
$bLongTitle = true;
?>
</div>
</div>
</div>
<?php
};
?>
</div>
<?php if ($bLongTitle) {?>
<script>.cardTitle br {display:none;}</script>
<?php } ?>
CSS-only solution - not viable for the OP?
Because the titles are aren't direct siblings, the only way would be to fix the height of all title. This isn't a desirable solution, as I'm sure titles can vary a lot in length so its impossible to pick a "default" height to suit every possibility, and even that's complicated by the responsive width of the columns potentially changing the heights dynamically.
But for the sake of completeness:
add a class (e.g. .cardTitle) to the title in your loop
identify suitable heights for the title with and without a line break, and set these in your CSS
add the corresponding class (e.g. wrapTitle) to your <p> if any title is too long in a loop (similar to adding a line break above)
CSS
p.cardTitle { height:20px; } /* example of the default height for title */
p.cardTitle.wraptitle { height:40px; } /* example of height for wrapped title */
PHP (after looping through SQL rows to fill $cards array as option (a) above)
<?php
foreach ($cards as $title => $category) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p class="cardTitle <?php if ($bLongTitle) echo "wrapTitle"; ?>"><? echo $title; ?></p>
<p>Category: <? echo $row["category"]; ?></p>
</div>
</div>
</div>
<?php
};
?>
jQuery
You could use jQuery to loop through all elements to calculate the heights, and set them all to the tallest.
You could write the code yourself (see How to make all div columns of the same height automatically with jQuery or Setting equal heights for div's with jQuery but there is a library available to do this for you: matchHeight
Using the library, all you need to do is include it on your page and call it like this (assuming you've added the class cardTitle to the <p> that holds your title)
jQuery(document).ready(function() {
$(".cardTitle").matchHeight();
});
I would perform a new SQL query first to see if any results have a title length of greater than 41 characters:
select count(*) from table where length(title)>41
And then set the result of this query to be a variable, e.g. $has41
You can then use an if statement within your loop ...
if($has41) {
// do something with $row['title']
} else {
// do something else with $row['title']
}
I am trying to learn php together with MYSQL. I have built the database on on the from end I have written the code below to bring in the website title from the database which works. However, I have two questions.
How would I get the result to display in <h1> tags?
Is this the cleanest way of pulling this value through?
Any help or advise greatly appreciated
<?php
include 'connection.php';
$sql = "SELECT VariableValue FROM VariableValues WHERE VariableID = '1'";
$result = $conn->query($sql);
while($header = $result->fetch_assoc()) {
echo $header["VariableValue"]. "<br>";
}
?>
To get a single row from db, you could use this:
$header_title = implode(mysqli_fetch_assoc(mysqli_query($conn, "SELECT VariableValue FROM VariableValues WHERE id = 1 LIMIT 1")));
Put a php variable between a html tag :
<tag><?php echo $var; ?></tag>
Eg :
<title><?php echo $header_title; ?></title>
You can echo all types of tags in PHP echo
for example:
echo '<div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div id="success_alert" align="center" class="alert alert-success">
<strong>Log in to download this chapter.</strong>
</div>
</div>';
I have echoed different types of bootstrap tags in echo. Similarly you can also echo all types of tags you want.
To displays it in tags, use <h1><?php echo $var; ?></h1> for example.
So have the following while loop which will output all the results for a SQL query carried out in PHP:
while ($row = mysqli_fetch_array($result))
{
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
$output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
echo "$output";
}
You can assume that $result will contain the table which I am reading on row at a time. The above code is working just fine but when I try to display the information in HTML (so that it actually looks nice) I run into a problem
If I do the following:
<html>
<section id="main" class="container 75%">
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<?php echo $output; ?>
</div>
</section>
</html>
It will only display the very last resort. I know that this happening because $output can only hold one string at a time, but I don't know any other way to display the information on the HTML. I though of possibly using an array to store all the strings, but the documentation doesn't show me how to set-up a dynamic array.
Does anyone here know how to display all the results of the search query in an HTML page?
You can do combine both php and html code like this:
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<?php
while ($row = mysqli_fetch_array($result)) :
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
$output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
echo "<div class=\"box\">$output</div>";
endwhile;
?>
This way you don't have to use an array to display the result.
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<?php
while ($row = mysqli_fetch_array($result)) {
$row = mysqli_fetch_array($result);
echo 'Restaurant name: '.$row['restaurant_name'];
echo 'Cusine: '.$row['cusine'];
// ...and so on
}
?>
</div>
You can have the loop produce the HTML inside your div with a table. I am not sure what your CSS is like for your box class, but this will certainly make it look better while printing out all of your results.
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<table>
<tr>
<td>Restaurant</td>
<td>Cusine</td>
<td>Wait Time</td>
</tr>
while ($row = mysqli_fetch_array($result))
{
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
echo "<tr><td>". $restaurant_name . "</td><td>" . $cusine . "</td><td>" . $wait_time . "</td></tr>";
}
</table>
</div>
You are overwriting your $output variable every loop, and then trying to echo $output later; it will only contain the data from the last iteration.
Instead, make $output an array containing your data and then loop over it for display purposes:
$output=array();
while ($row = mysqli_fetch_array($result)) :
$output[]=$row;
endwhile
Then you can loop over the $output array to build an output for each restaurant:
foreach($output as $value):
$returnDetails='<div class="box">';
$returnDetails.='Resturant Name: '.$output['restaurant_name'].'<br />';
// etc. for all details
$returnDetails.='</div>';
echo $returnDetails;
endforeach;
Added benefit of this way: you have access to the $output array if you ever wanted to access a single row outside the context of the loop
Easy one! I'm trying to code a cheap forum. Coming from a C background, I started to noticed something strange about PHP. While having a function return a string (HTML) inside of a DIV into place, the browser would not print the </DIV> - even when it's echo'ed by itself.
Does PHP decide when it wants to echo certain DOM elements or have limitations on HTML output?
echo "Start<div id='Forum'>";
echo "Forum";
GetFullList();
echo "</div>";
Where, GetFullList() consists of:
function GetFullList(){
$sql="SELECT * FROM `Forum` WHERE `IsReply` =0";
$result=mysql_query($sql);
if (!$result){
echo mysql_error();
}
if($result){
while($ForumEntry = mysql_fetch_assoc($result)){
$IsReply = $ForumEntry["IsReply"];
$ParentPost = $ForumEntry["ParentTopic"];
$f_User = $ForumEntry["User"];
$f_Replies = $ForumEntry["Replies"];
$f_Views = $ForumEntry["Views"];
$f_Time = $ForumEntry["Time"];
$f_Post = $ForumEntry["Post"];
$f_Topic = $ForumEntry["Topic"];
$f_Index = $ForumEntry["Index"];
echo DisplayPost($f_User, $f_Replies, $f_Views, $f_Time, $f_Post, $f_Topic, $f_Index);
GetChildPostsOf($ParentPost);
}
}
}
And DisplayPost() is built as such:
function DisplayPost($f_User, $f_Replies, $f_Views, $f_Time, $f_Post, $f_Topic, $f_Index){
$PostBlock = "<div id='Grp_Cell' style='width:930;background-color:#999999;text-align:left;'><div id='Grp_Cell' style='float:left;'><div id='Tbl_Cel'>User: ".$f_User."</div><div id='Tbl_Cel'>Replies: ". $f_Replies."</div><div id='Tbl_Cel'>Views: ".$f_Views."</div><div id='Tbl_Cel'style='background-color:777777;height:112;'>Post started on ".$f_Time.". </div></div><div id='Grp_Cell' style='float:right;width:600;'><div id='Tbl_Cel'>Subject: ".$f_Topic."</div><div id='Tbl_Cel' style='background-color:777777;height:150;'>". $f_Post."</div><a onClick='Reply(".$f_Index.");Filter();'><div id='Tbl_Cel' style='background-color:#888888; height:50; width:50; float:right; padding:2;border-color:black; border:2;'><br>Reply</div></a></div>";
return $PostBlock;
}
(Displays a div scaffolding for DB results: the post.)
When I try to echo "< /div>" after GetFullList(), the result is not printed in HTML, leaving the rest of the page to be encompassed under the malformed div.
There are 10 opening divs and 9 closing divs in $PostBlock. A closing </div> should be added where necessary. An easy way to see what the output looks like is to break it into lines like this:
$PostBlock = "
<div id='Grp_Cell' style='width:930;background-color:#999999;text-align:left;'>
<div id='Grp_Cell' style='float:left;'>
<div id='Tbl_Cel'>User: ".$f_User."</div>
<div id='Tbl_Cel'>Replies: ". $f_Replies."</div>
<div id='Tbl_Cel'>Views: ".$f_Views."</div>
<div id='Tbl_Cel'style='background-color:777777;height:112;'>Post started on ".$f_Time.". </div>
</div>
<div id='Grp_Cell' style='float:right;width:600;'>
<div id='Tbl_Cel'>Subject: ".$f_Topic."</div>
<div id='Tbl_Cel' style='background-color:777777;height:150;'>". $f_Post."</div>
<a onClick='Reply(".$f_Index.");Filter();'><div id='Tbl_Cel' style='background-color:#888888; height:50; width:50; float:right; padding:2;border-color:black; border:2;'><br>Reply</div></a>
</div> ";