I'm building a food menu on a webpage. This menu includes drink items like Wine and Beer. Currently, they are categorized by Red or White and the type of wine (Pinot Grigio, Chardonnay, etc.). I have entered these wine items into a MySQL database with the following columns/values:
id(int), name(varchar), type(varchar), price_bottle(decimal), price_glass(decimal), red(bool)
My Current code:
$result = mysql_query("SELECT * FROM Wines WHERE type = 'Pinot Grigio' ");
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$type = $row['type'];
$price_bottle = $row['price_bottle'];
$price_glass = $row['price_glass'];
echo
"<div class='foodmenu-item'>
<div class='foodmenu-text'>
<h2>" . $type . "</h2>
<p>" . $name . "</p>
</div>
<div class='foodmenu-price'>
<p>$" . $price_bottle . " / " . $price_glass . "</p>
</div>
</div>";
}
Which is fine if I wanted to display each item out individually, but I want to Group by 'type' of wine (Pinot Grigio, Chardonnay, etc.) and then list each name of the wine under that 'type' so my CSS looks neat and organized.
For Example:
PINOT GRIGIO
Nobllissimo
Riff
CHARDONNAY
The Crusher
Bogle
Using the "GROUP BY" SQL syntax only displays the first result with my current code. All my attempts at making a foreach statement result in error, I'm not sure where to turn next.
How can I achieve this?
good manner is don't simply use "*", but list of columns
(reason: select only data which realy want to use - better performance, second if you later want add or change columns in the table then your life will be simplier ;-) )
I think you can try, select all from small table and only sort the data - type and name, then in while cycle do it group about type for your menu. Then you need only one query send to database and have all of it. Assumption is Wines is only small table, because select all consume a memory.
SELECT type, name, price_bottle, price_glass
FROM Wines
ORDER BY type, name;
Have you tries using 2 queries nested? Like this:
$result = mysql_query("SELECT DISTINCT(type) FROM Wines ORDER BY type");
while($row = mysql_fetch_array($result)) {
$type = $row['type'];
echo "<div class='foodmenu-item'>
<h2>" . $type . "</h2>";
$result2 = mysql_query("SELECT * FROM Wines WHERE type = '".type."' ");
while($row2 = mysql_fetch_array($result2)) {
$name = $row2['name'];
$price_bottle = $row2['price_bottle'];
$price_glass = $row2['price_glass'];
echo "
<div class='foodmenu-text'>
<p>" . $name . "</p>
</div>
<div class='foodmenu-price'>
<p>$" . $price_bottle . " / " . $price_glass . "</p>
</div>";
}
echo "</div>";
}
Related
Need to showup the Qty of "IDs" or "Class" from a Site in my header.
It a job-site, i want to count the IDs or class of my Job Listings and show the number in my header (Menu).
How is it possible? With "getElementsByTagName" it works like a charme. Tried with "H3" Tags, but i have to many h3 on the site, so the qty / number is not correct.
my code now:
<?php
$htmlString = file_get_contents('https://www.mywebsite.de/unternehmen/jobs/');
//Create a new DOMDocument object.
$htmlDom = new DOMDocument;
//Load the HTML string into our DOMDocument object.
#$htmlDom->loadHTML($htmlString);
//Extract all h3 elements / tags from the HTML.
$h3Tags = $htmlDom->getElementsByTagName('h3');
$jobanzahl = $htmlDom->getElementById('jobtitel')->nodeValue;
echo "Total H3 Tags: ". count($h3Tags)."<br/>";
It would be much easier to use the SELECT COUNT with your database, because you can manage which job offers are active and which are not. You can also ORDER BY starting date if you wish !
Here is the dataset I used for this example :
Each job has a unique id (int) as a primary key, a title (varchar), a description (text), a starting date (date) and a status (active or not - boolean). You can archive inactive offers for monthly or yearly reports, but you must count only active ones.
At first, I display the offers on a very basic html page :
$sql = "SELECT * FROM job";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
echo "<h1>JOBS</h1>";
echo "<br>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "<p><small>Starting on : " . $row['start_date'] . "</small></p>";
echo "<hr>";
}
}
And then, I count and display the number of active offers :
$sql = "SELECT COUNT(*) AS c FROM job WHERE isActive = 1";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<p>There are " . $row['c'] . " offers</p>";
}
Here is the final result :
Finally, you should look at this codepen to circle the result :
https://codepen.io/jnbruno/pen/vNpPpW
I have a website where drinks are sorted by brand and by 'product description' or 'grade'. When visiting a page for a particular drink, amongst other menus one of the menus shows the product description of the current drink (and if clicked on goes to a page showing other drinks from different brands with the same product description) and on hover over shows drinks from the same brand with a different product description (the hover effects are done with simple CSS).
This all works fine - however some brands only have a single product, meaning that the menu appears but with zero height (except for the border) and no data in it, which doesn't look good. So what I want is an IF statement that'll detect whether there are any results from the MySQL query and use different CSS depending on the result - however I just can't seem to find a way that works.
($Brand and $ProductDescription are defined earlier, and refer to the current drink)
<?php
$sql = "
SELECT DISTINCT
ProductDescription
FROM
WebDatabaseText
WHERE
Brand='$Brand' AND
ProductDescription<>'$ProductDescription' AND
Hide=0 AND
Language='$Language' AND
Website='$Website' AND
ProductDescription <> '(brand notes)'
ORDER BY
ProductDescription
";
$result = $conn->query($sql);
If there's at least one result:
echo "<ul id='nav' class='drop'>
<li><a href='/english/grades/?Grade=". $ProductDescription . "'>" . $ProductDescription . "</a> ";
echo " <ul>";
while($row = $result->fetch_assoc()) {
echo "<li><a href='/english/products/?Brand=" . $Brand . "&ProductDescription=". $row["ProductDescription"] . "'>" . $row["ProductDescription"] . "</a> </li>";
}
echo " </ul> </li> ";
echo " </ul>";
If there's nothing:
echo "<ul id='nav' class='drop'>
<a href='/english/grades/?Grade=". $ProductDescription . "'>" . $ProductDescription . "</a> </ul>
?>
Number of found records is in mysqli_num_rows function.
if ($result->num_rows > 0) {
while (...) {
...
}
} else {
echo 'Nothing found';
}
Try
if ($result->num_rows > 0) {
//your while loop here
} else {
//do something
}
New to php environment, what I am trying to do is create a list using php and MySQL database. see below
-----my output requirements info ------
main page heading
subheading1 (content of brandtype=1)
1111
2222
3333
4444 ( I want these as a hyperlink to open in the same webpage)
subheading2 (brandtype=2)
5555
6666
7777
8888 ( I want these as a hyperlink to open in the same webpage)
my code below
// Connect to database server
include 'xxxxxyyyyzzzz.php';
$conn = mysql_connect($db_host,$db_username,$db_password);
mysql_connect($db_host,$db_username,$db_password) or die (mysql_error ());
mysql_select_db($db_database,$conn) or die(mysql_error()); // Select database
echo "<h1>main webpage heading</h1>";
echo "<h3>my subheading</h3>";
// SQL query
$strSQL = "SELECT * FROM table name WHERE brand type='1','Software' ORDER BY serviceName ASC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
$strName = $row['serviceName'];
$strLink = "<a href = 'person.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
// include 'emaild.php';
}
// Close the database connection
mysql_close();
?>
</ul>
</body>
</html>
end of my code
I am getting a listing ok, but have to put in subheading manually (e.g. echo "main title page names"; echo "subheading title"; depending on the brand type ?
how can tweak my code so that where my brand type = 1 it prints a heading brand type1 and then prints out the items for that brand 1 underneath it, if there are no items , then it does not print subheading (brand type=1) and goes to the next to print subheading for brandtype=2 and lists the content underneath it.
I can make list items underneath each subheading as links to a webpage but it does not work, how can I make these list items open on the same webpage with more details of product and I would use back button to go previous list webpage...thanks in advance..singhy
Are the brand names in a different table where it can be read? If it's not you can do it manually still, but will much more ease (See below). If so, please let us know where that is located.
SendBrandListings(1, "Brand 1 Header");
SendBrandListings(2, "Brand 2 Header");
function SendBrandListings($brandId, $heading){
echo "<h3>$heading</h3>";
$strSQL = "SELECT * FROM table name WHERE brand type='$brandId','Software' ORDER BY serviceName ASC";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
$strName = $row['serviceName'];
$strLink = "<a href = 'person.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
echo "<li>" . $strLink . "</li>";
}
}
UPDATE
If your brand name is in the same table, let's say the field is brandName - you would modify you current loop to this (simplified for demo purposes).
First, you'll want to ensure that your results are sorted by Brand FIRST, then by service name. This is because we will be looping through the services in the order they are received in. This will arrange items of a like brand together. So make sure your SQL statement's sorting argument looks like this:
ORDER BY brandName, serviceName ASC
Simply keep track of the last Brand Name you displayed, and if it changes, display the new one.
$c = 0; //Variable to keep count of categories
$lastBrand = ''; //Declare a variable to track the last displayed Brand Name
while($row = mysql_fetch_array($rs)) {
//If the brand name has changed, display it and update the tracking variable
if ($lastBrand != $row['brandName']){
$lastBrand = $row['brandName'];
//If this isn't the first category, end the previous list.
if ($c>0) echo "</ul>";
echo '<h3>'.$row['brandName'].'</h3><ul>';
$c++;
}
$strName = $row['serviceName'];
$strLink = "<a href = 'person.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
echo "<li>" . $strLink . "</li>";
}
I'm designing a website for a neighbor for a potential restaurant he wants to open. I need to create a page for testimonials/review. I'd like to code it so that the number of stars is in a SQL, I'm just not sure how to do it.
Essentially what I'm looking for is a way to determine the integer of the ratings field (1-5) and for each number, display a star image.
So:
if rating = 1, display star.png once
if rating = 2, display star.png twice
...
if rating = 5, display star.png five times
I'm just not sure how to write the code to do so.
The website is being written in PHP and CSS. I'd like to avoid JQuery, Javascript, .NET, and so forth, as I'm not as familiar with them and will be the one keeping the site up to date.
Here's what I've got so far, but it's not working right, and I get a syntax error:
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result))
{
IF (Rating = "1"()){
echo '<img src="star.png">' . }
ELSE IF (Rating = "2"()){
echo '<img src="star.png"><img src="images/star.png">' . }
Else IF (Rating = "3"()){
echo '<img src="star.png">star.png"><img src="images/star.png">' . }
ELSE IF (Rating = "4"()){
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png">' . }
ELSE
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png"><img src="images/star.png">' .
"<br/> <b>" .
$row['Name'] .
"</b> <em>" .
$row['City'] . $row['State'] . $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>"
}
?>
Use a select statement to get the ratings for a place from your database.
Store the result in a php variable (lets call it $rating)
Use php logic to output number of stars (in html obviously) based on value of $rating.
Hope that helps :)
I would recommend 3 tables for this idea.
Users Table
UserRatings Table
Dish Table
Users table is used to store just that. User information. Possibly a username, password, first name, last name for example. The table should have a primary key. Call it UsersID. It should auto increment itself and be unique for every row.
The Dish table is next. Put a dish name in it. It should have a primary key as well. Call it DishID.
Lastly is the UserRatings table will store UserRatingsId, Rating, InsertTimeStamp, UpdateTimeStamp.
Use a loop to output your HTML based on your rating.
$rating = 4; //Figure this out in your script and set accordingly
for($i = 0; $i < $rating; $i++) {
echo '<img src="star.png" />';
}
Should print out four stars for you.
Help from a friend:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$starCount = 0;
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result)) {
$starCount = $row['Rating'] ;
while ($starCount > 0) {
echo '<img src="images/star.png">';
$starCount -- ;
}
$starCount = 0;
echo "<br/> <b>" . $row['Name'] . "</b> - <em>" .
$row['City'] .", ". $row['State'] ." ". $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>" ;
}
?>
$number=$row->rating ;
$middle="";
$first="<td width='200' align='left'>";
for($x=1;$x<=$number;$x++) {
$middle=$middle.img($fullimage_properties);
}
if (strpos($number,'.')) {
$middle=$middle.img($halfimage_properties);
$x++;
}
while ($x<=5) {
$middle=$middle.img($blankimage_properties); ;
$x++;
}
echo $last=$first.$middle."</td>";
While dynamically generating a page with different types of contents , the "post" content is appearing above the static content which is being generated.I want it the other way around. Does there appear to be anything in my code that would make this happen, or do you think the problem has something to do with my database? Thanks.
$query = "SELECT * FROM content WHERE pages LIKE '%$pageID%'";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// Display pages's static content
if ($row['type'] == "static") {
echo "
<h2>" . $row['tile'] . "</h2>
<content>" . $row['body'] . "</content>
";
}
// Display pages's posts
else {
echo "
<h2>" . $row['tile'] . "</h2>
<content>" . $row['body'] . "</content>
";
}
SELECT * FROM content WHERE pages LIKE '%$pageID%' ORDER BY type desc
Add this to the end of your query:
ORDER BY CASE WHEN type = 'static' THEN 0 ELSE 1 END