I have managed to output the average rating in a number format, but i would like to output it by using the star method as well.
This is my code so far that outputs the average rating by using numbers;
<?php
$sql = "
SELECT round(avg(`rate`),2) AS `average_rate`, count(`rate`) AS `num_of_rating`
FROM tbl_rating
WHERE hotel_id = '$id' ";
$query = mysqli_query($con,$sql);
$rating = mysqli_fetch_assoc($query);
?>
<div>
<h4 style="color: #1478FF; font-size:30px; font-family: " > <?php echo $rating['average_rate']; ?> Avergae rating </h4>
</div>
For instance;Stars
Please give this a try:
<?php
$sql = "
SELECT round(avg(`rate`),2) AS `average_rate`, count(`rate`) AS `num_of_rating`
FROM tbl_rating
WHERE hotel_id = '$id' ";
$query = mysqli_query($con,$sql);
$rating = mysqli_fetch_assoc($query);
?>
<div>
<h4 style="color: #1478FF; font-size:30px; font-family: " > <?php echo $rating['average_rate']; ?> Average rating </h4>
<?php
$limit = floor($rating['average_rate']);
$remainder = $rating['average_rate'] % 1.0;
for( $i = 0; $i<$limit; $i++ ) {
echo ("<img src=\"\\images\\fullstar.jpg\" />");
}
if ($remainder >= 0.5) echo ("<img src=\"\\images\\halfstar.jpg\" />");
?>
</div>
I'm not sure this will work. I have no way of testing the code, I'm a C# and ColdFusion developer. This is what a few minutes on Google gave me.
To make this work, you need images of a full star called fullstar.jpg and of a half start called halfstar.jpg. They both need to be in a folder names images in your project root.
Related
I have some HTML in a variable that I'd like to loop 4 time per row. I am making a couple of queries first. In one I get the number of rows and store it in a variable. The second, I am looking to fetch the associated data that I will need to display.
$results = $dbCon->query("SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($results);
$res = $dbCon->query($results);
$data = $res->fetch_assoc();
$link = $data['link'];
$title = $data['title'];
$image = $data['image'];
$imgAlt = $data['imgAlt'];
Third, I store what I want to display in a variable. The HTML I plan on displaying looks something like this
$html = printf("<div style=\"text-align:center; max-width:270px; white-space:normal; word-wrap:break-word; border-left:1em solid transparent; border-right:1em solid transparent; text-overflow: ellipsis; float:left;\">
<a href=\"%s\">
<img style=\"width:270px; height:232px; margin-bottom:40px; border-radius:45px; -moz-border-radius:45px; -webkit-border-radius:45px; box-shadow:0px 0px 3px #fff; -moz-box-shadow:0px 0px 3px #fff; -webkit-box-shadow:0px 0px 3px #fff;\" src=\"images/recentshoots/%s\" alt=\"%s\" />
<p>%s</p> <br /></a>
</div>", $link, $image, $imgAlt, $title);
Next, I would like to loop the 20 items per page in 4 items per row. This is where I am having some trouble. My issue is that the number of characters in the $title are always different so the layout breaks apart. At first a tried a simple way using css and php to do a str_pad() but it doesn't seem to work right with empty spaces. I always get some containers that are taller than others which distorts my row. So I did some research in this platform to model after someone else example.
I m having some trouble with what I found because the examples I've seen have information missing that I need to understand how to modify my own. I have seen it done with foreach and while loops. Can someone help me find a way to understand this better?
How can I loop the data retrieved and make sure that only 4 per row exist in a page of 20 items? Thank you so much for your help. I started with something like this
$startingPoint = 1;
echo "<div class=\"row\">";
foreach($startingPoint < 4){ //this foreach is not even starting the right way, how can I fix this?
echo $html;
}
Can I use a foreach? or a while loop? or do-while?
which one is the best solution and the fastest or most efficient way to go? The shorter the code the better.
Foreach loops are used for array datatypes whilst a while loop can be used for booleans and more.
What you're looking for is a for loop, this allows your to set a counter and each time the loop is ran it adds to a counter. Once the expression is met, it ends the loop.
for($i = 1; $i == 4; $i++)
{
echo 'Loop ' . $i . ': This will loop 4 times';
}
However, you could fix your foreach by using this snippet:
$startingPoint = [1,2,3,4];
foreach($startingPoint as $start)
{
echo $html;
}
Since there are 4 items inside the array, the loop will continue 4 times.
Your SQL is returning more than one row of data thus creating $data to become multidimensional, your loop therefore may not work how its written, you could try this:
for($i = 1; $i >= $limit; $i++)
{
print_f(<!-- html here -->, $data[$i]['column']);
}
You can try this code. Full pagination and view:
Example: index.php
<?php
//get page id for pagination and limit query
$limit = 4;
if(isset($_GET["page"]))
$page = intval($_GET["page"]);
else
$page = 1;
$total = $limit * $page;
$start = $total - $limit;
//GEt data from database. I have used mysqli for testing purpose.
$conn=mysqli_connect("localhost","root","","dbname");
$result = mysqli_query($conn, "SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($result);
?>
<!--Your html code what you want-->
<table>
<tr>
<th>Title</th>
<th>Image</th>
<th>Link</th>
</tr>
<!--loop inside html-->
<?php while($data = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $data['title']; ?></td>
<td><img src="<?php echo $data['image']; ?>" alt="<?php echo $data['imgAlt']; ?>"> </td>
<td>Link</td>
</tr>
<?php } ?>
</table>
<?php
/**======== Pagination Url generate=============*/
$totalPages = ceil($total/$limit);
if($page <=1 ){
" <span style='font-weight: bold;'> < Prev </span> ";
}else{
$j = $page - 1;
echo " <a href='index.php?page=$j'>Prev</a> ";
}
for($i=1; $i <= $totalPages; $i++){
if($i<>$page){
echo " <a href='index.php?page=$i'>$i</a> ";
}else{
echo " <span style='font-weight: bold;'>$i</span> ";
}
}
if($page == $totalPages ){
echo " <span style='font-weight: bold;'>Next ></span> ";
}else{
$j = $page + 1;
echo " <a href='index.php?page=$j'>Next</a></span> ";
}
?>
I'm working on an event scheduler site and I am currently stuck as I'm using a Months table (with id & month as the headers) to group my results by month. Due to this, if I try to schedule an event for January 2016, it successfully puts it into the month I choose as intended, but understandably puts it into 2015.
I'm looking to get some help on extending this beyond the end of the current year and adding functionality for different years.
I would happily use another method than using my current table setup, so any tips or suggestions would be appreciated.
Current code is as follows:
<?php include 'includes/connect.php';
include 'includes/header.php';
$curMonth = date("n"); ?>
<b>Upcoming Trip Information:</b><br><br>
<?php
$res = mysql_query("SELECT * FROM months ORDER BY id");
while ($rows = mysql_fetch_array($res)) {
if($rows['id'] >= $curMonth ){
$monthname = $rows['month']; ?>
<table cellpadding="0" cellspacing="3" width="100%">
<tr>
<td>
<?php
$tid = $_GET['transporter'];
$check = mysql_query("SELECT * FROM trips WHERE monthname(start_date) = '" . $rows['month'] . "' AND tid = '$tid'");
$check = mysql_num_rows($check);
if ($check < 1) {
echo "";
} else { ?> <h2><?php echo $monthname; ?><?php } ?></h2></td></tr> <tr> <?php $cmonth = date('F');
$tid = $_GET['transporter'];
$res1 = mysql_query("SELECT * FROM trips WHERE monthname(start_date) = '$monthname' ORDER BY start_date");
while ($rows = mysql_fetch_array($res1)) {
$trid = $rows['trid'];
$trip_start = $rows['trip_start'];
$trip_end = $rows['trip_end'];
$start_date = $rows['start_date'];
$end_date = $rows['end_date'];
$colour = $rows['colour'];
$stime = strtotime($start_date);
$startt = date("l jS", $stime);
$etime = strtotime($end_date);
$endt = date("l jS", $etime); ?>
<td valign="middle" style="height: 100px; background-color: #4b99ed; text-align: center;">
<div style="font-size: 17px; color: #ffffff;"><?php echo $trip_start; ?> to <?php echo $trip_end; ?></div>
<div style="font-size: 15px; color: #ffffff;"><?php echo $startt; ?> - <?php echo $endt; ?></div>
</td>
<?php } } } ?>
</tr>
</table> <?php include 'includes/footer.php'; ?>
If possible I would like to maintain the results layout..
You could try, instead of using a months table, using the start_date column of your trips table.
Try changing your query:
SELECT trips.*, DATE_FORMAT('%M, %Y', start_date) as `dt`
FROM trips
WHERE tid = '$tid' /* This is bad, please prepare or escape your variables*/
ORDER BY `dt` ASC
You then won't have to do the first query to get all the months and loop through them. If you must have empty containers for each month, try using that query, but loop through a PHP-generated array of months to display.
I want to select every photo from my database, then display them grouped by month. I have that code here:
<?php
if (isset($_COOKIE['user_id'])) {
if (!isset($_GET['user_id'])) {
$user_id= $_COOKIE['user_id'];
} else {
$user_id= $_GET['user_id'];
}
$connect= mysqli_connect("localhost", "root", "", "si");
$query= "SELECT * FROM posts WHERE user_id= $user_id ORDER BY date DESC";
$result= mysqli_query($connect, $query)
or die('error with query');
$date = "0";
while ($row= mysqli_fetch_array($result)) {
if ($date != $row['date']) {
echo "<p> ".$row['date']."</p><br/>";
$date = $row['date'];
}
echo '<img src="'.$row['picture']. '"/>' . "<br/>";
}
}
?>
The only problem is that my code displays EVERY image from each month, this makes for an excessively large page. I want to limit my results to only 8 per month (or less if there isn't event 8 pictures for that month), then display a "show more..." link if there are more than 8. I know how to add a LIMIT to my initial query, but that won't work for this scenario. What can I do?
Here is how I want it to look:
add LIMIT $start, $numToDisplay
to your SQL statement, and use PHP to calculate the new values for the $start variable.
e.g. $pageNum = $_GET["page"] and 8 images per page means you can calculate that:
$numToDisplay = 8;
$start = ($pageNum-1)*$numToDisplay;
What you need to do is monitor picture count
$pickLimit = array ();
while ( $row = mysqli_fetch_array ( $result ) ) {
if ($date != $row ['date']) {
echo "<p> " . $row ['date'] . "</p><br/>";
$date = $row ['date'];
}
$pickLimit [$date] = isset ( $pickLimit [$date] ) ? $pickLimit [$date] : 0;
if ($pickLimit [$date] > 7)
continue;
echo '<img src="' . $row ['picture'] . '"/>' . "<br/>";
$pickLimit [$date] ++;
}
This is what is known as "greatest n per group" query. If you search on here there are many examples with different solutions. Here is one of them -
SELECT *
FROM (
SELECT
tmp.*,
#r := IF(#m=DATE_FORMAT(`date`, '%Y%m'), #rank + 1, 1) rank,
#m := DATE_FORMAT(`date`, '%Y%m')
FROM (
SELECT *
FROM posts
WHERE user_id = $user_id
ORDER BY date DESC
) tmp, (SELECT #m:=NULL, #r:=NULL) initvars
) tmp2
WHERE rank <= 8
This could be easily done using the php script whitch you already have and some css tricks, that are also used for creating an animated slider/carousel. Something like this:
<div id="carousel">
<div id="slider">
<?php foreach($images as $img) { ?>
<div class="image">
<img src="<?php echo $img; ?>" />
</div>
<?php } ?>
</div>
</div>
As for the css:
#carousel {
width: 900px; /* how much you need */
height: 100px; /* how much you need */
overflow: hidden;
}
#slider {
width: auto;
height: 100px;
}
.image {
float: left;
}
i have a question in regards to displaying a visual bar comparing mysql values.
i have the following two scripts :
<?php
require_once("inc/common.inc.php");
session_start();
$SQL = "SELECT * FROM db WHERE id = $user[id] LIMIT 1";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['actual value'] . "<BR>";
}
?>
and
<?php
require_once("inc/common.inc.php");
session_start();
$SQL = "SELECT * FROM db WHERE id = $user[id] LIMIT 1";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['max value'] . "<BR>";
}
?>
these two queries show me the actual value and the max value of my user's health.
as of now im printing both values next to each other like 95/100.
i would like to display the above in form of a progress bar according to max and actual.
Any ideas or sugestions would be greatly appreciated.
Thank you.
the below answer doesnt seem to work.
For e.g.
<?php
$percent = intval($actual_value*100/$max_value);
?>
<div style="width: 200px; background-color: green;">
<span style="width: <?php echo $percent;?>%; background-color: red;"></span>
</div>
$max_value should be greater than zero of course :)
you could go with a JS progress bar. Assign one value to each progress bar, animate and this should do the trick
I have this PHP code :
$query = "SELECT * FROM news WHERE news_active = 1 AND news_type = 1 ORDER BY id DESC";
$q2 = "SELECT * FROM st_photos WHERE id = 4 LIMIT 1";
$r2 = mysql_query($q2);
$row22 = mysql_fetch_array($r2);
$news_set = mysql_query($query);
$news_set2 = mysql_query($query);
if (mysql_num_rows($news_set) != 0) {
$r = mysql_fetch_array($news_set);
echo "<div id=\"d_coll\">
<div id=\"top_text\">$row22[img]</div>
<div id=\"d_image\"><img id=\"larg_p2\" src=\"photos/$r[news_image]\" width=\"320\" height=\"250\" border=\"0\"></div>
<div style=\"width:300px\"><div id=\"n_text2\">$r[news_part_en]</div>
</div>
</div>";
}
if (mysql_num_rows($news_set2) != 0) {
while ($news = mysql_fetch_array($news_set2)) {
echo "<div id=\"n_col\">
<div id=\"n_tittle\">$news[news_tittle_en] <img src=\"images/bu3.png\" border=\"0\" align=\"middle\"></div>
<div id=\"im\"><img onMouseOver=\"MM_swapImage('larg_p2','','photos/$news[news_image]','imgs[$news[id]]','','photos/$news[news_image]',1);up2('$news[news_part_en]')\" onMouseOut=\"MM_swapImgRestore()\" name=\"imgs[$news[id]]\" id=\"imgs[$news[id]]\" src=\"photos/$news[news_image]\" width=\"50\" height=\"50\"></div>
<div dir=\"ltr\" id=\"n_div\">$news[news_part_en] <div class=\"mo\">MORE</div></div>
</div>";
}
echo "<div align=\"right\" class=\"arr\"><img src=\"images/prev.png\"> <img src=\"images/next.png\"></div>";
}
There are 2 images at the end of the code (prev & next), I want to use them to do pagination but I don't want to view any numbers, only these 2 images.
How I can do that?
I think we can do that by using JQuery library, but I don't know how to use it.
Thanks in advance.
you can use one of many plugins, for example here .
you must just remoove thе numbers. you can, i believe;)
or you can write the script by yourself.
i'll give you only an idea. let's assume you have 30 rows( from DB).put them into <div> tags, and increase the id of div. the display proparty of first <div> you must set to '', and all others to none. and then, onclick on your buttons, you just change display proparty of div elements...