PHP Group sql query under the same title - php

I am trying to do a restaurant site where the people can see the menu.
I have a table that looks like this:
And now I want to output this data according the title:
Pizza
Ham & Cheese $150
Onion & Cheese $120
Salad
Caesar $70
Tomate & Olives $60
Dessert
Icecream $110
Vanilla Cake $90
-
Well at the future the menu_title can be changed by the client... That means the title need to be retrieved also from the database.
Here is the code I am trying but I don't have idea how to add the content below the title:
<?PHP
$sql_product="SELECT * FROM cc_restaurants_menu WHERE menu_asoc='$asoc' AND menu_type='product' GROUP BY menu_title";
$stmt_product = $conn->prepare($sql_product);
$stmt_product->execute();
$result_product = $stmt_product->setFetchMode(PDO::FETCH_ASSOC);
if($result_product > 0) {
while($row = $stmt_product->fetch()) {
echo '<h3>'. $row['menu_title'] .'</h3><br><p>'. $row['menu_product'] .'</p>';
}
}
?>
But this code only output the title and the first row :S
Any idea?
EDIT
I got 2 answer correct:
OPTION 1
$sql_product="SELECT * FROM cc_restaurants_menu WHERE menu_asoc='$asoc' AND menu_type='product'";
$stmt_product = $conn->prepare($sql_product);
$stmt_product->execute();
$result_product = $stmt_product->setFetchMode(PDO::FETCH_ASSOC);
if($result_product > 0) {
while($row = $stmt_product->fetch()) {
$menuArr[$row['menu_title']][] = '<p>'. $row['menu_product'] . ''. $row['menu_product_price'] . ''. $row['menu_product_desc'] .'</p>';
}
foreach($menuArr as $menuTitle => $productArr){
echo '<h3>'. $menuTitle .'</h3></br>';
foreach($productArr as $key =>$productname){
echo '<p>'. $productname .'</p>';
}
}
}
OPTION 2
$sql_product="SELECT * FROM cc_restaurants_menu WHERE menu_asoc='$asoc' AND menu_type='product' ORDER BY menu_title";
$stmt_product = $conn->prepare($sql_product);
$stmt_product->execute();
$result_product = $stmt_product->setFetchMode(PDO::FETCH_ASSOC);
$title = "";
while ($row = $stmt_product->fetch()) {
if ($row['menu_title'] != $title) {
echo '<h3>'.$row['menu_title'].'</h3><br>';
$title = $row['menu_title'];
}
echo '<p>'.$row['menu_product'].'</p><p>'.$row['menu_product_price'].'</p>';
}

Please try this
$sql_product="SELECT * FROM cc_restaurants_menu WHERE menu_asoc='$asoc' AND menu_type='product'";
$stmt_product = $conn->prepare($sql_product);
$stmt_product->execute();
$result_product = $stmt_product->setFetchMode(PDO::FETCH_ASSOC);
if($result_product > 0) {
while($row = $stmt_product->fetch()) {
$menuArr[$row['menu_title']][] = $row['menu_product'] . " ".$row['menu_price'];
}
foreach($menuArr as $menuTitle => $productArr){
echo '<h3>'. $menuTitle .'</h3>';
foreach($productArr as $key =>$productname){
echo '<p>'. $productname .'</p>';
}
}
}

I would prefer doing this:
Just SELECT * ... ORDER BY menu_title, and then sort it in PHP:
$title = "";
while ($row = $stmt_product->fetch()) {
if ($row['menu_title'] != $title)
echo '<h3>'.$row['menu_title'].'</h3><br>';
$title = $row['menu_title'];
echo '<p>'.$row['menu_product'].'</p>';
}

GROUP BY will return 1 row for each unique value - which is why you are only seeing 1 row.
Option 1
Use this query to output the 'Menu Title' only, passing the Menu Title to a second query inside the loop, to return rows matching the Menu Title.
Option 2
Remove the GROUP BY in your query, loop through the results using 'logic' to only output the menu Title if it is different from the previous Menu Title.

Related

How to display count results with multiple keywords anywhere in a database field

We have a page tcount.php where we fetch counts for BOTH keyword1 and keyword2 occuring anywhere in a text field in mysql database using php script. The counts are displayed as hyperlinks. Now after that, we want that if someone clicks on the hyperlinks, they will see the detailed results in showt.php page showing those rows of the database corresponding to only those text field containing BOTH keywords.
The url of the second page showt.php is like
http://www.example.com/page.php?keyword=keyword1+keyword2
But problem is that it shows only those results which have keyword1 and keyword2 next to each other.
For example, keyword1 is car and keyword2 is cap and our text fields are as follows -
car cap
car best cap
car new
Then, we want it to show 1. and 2. as results but it is showing only no. 1 in the results page.
Please help.
Edit -
This is the code in page 1 tcount.php -
$kewyWordQ = $db->query("SELECT keywords FROM Table1 ");
<?php
while($row = $kewyWordQ->fetch(PDO::FETCH_ASSOC))
{$keyWord = $row['keywords'];
$keyWordsArr = explode(" ", $row['keywords']);
$countData = array();
$keyIndex = 0;
$tIndices = array();
$tArr = array();
$tIndices[] = "-1";
foreach($keyWordsArr as $keyword)
{
$t = $db->query("SELECT user_name FROM Table2 WHERE
t_text LIKE '%$keyWordsArr[$keyIndex]%'");
$tArr[] = $t;
while($row2 = $tweet->fetch(PDO::FETCH_ASSOC))
{
$found = TRUE;
foreach($keyWordsArr as $keyword1)
{
$ret = strpos(strtolower($row2['t_text']),
strtolower($keyword1));
if(($ret == 0) &&
strcmp(strtolower($row2['t_text'][0], strtolower($keyword1)[0])))
{
$found = FALSE;
break;
}
}
if($found == TRUE)
{
$ret = strpos($tIndices, $row2['t_id']);
if(($ret == 0) && strcmp($tIndices[0],
$row2['t_id']))
{
$tIndices[] = $row2['t_id'];
$countData[] = $row2['user_name'];
}
}
}
$keyIndex++;
}
?>
<tr><td><?php echo $row['keywords'];?></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo count($countData); ?
></a></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo
count(array_unique($countData)); ?></a></td>
</tr>
<?php } ?>
And this is the code in page 2 showt.php -
$keywords = $_GET['keyword'];
$sql="SELECT col1, col2, col3 from t AS s INNER JOIN users AS p ON
s.user_name=p.user_name where s.t_text LIKE '%$keywords%'
The WHERE statement of your query should look like:
WHERE my_text_field LIKE ?
and the binded parameter should be %$keyword1%$keyword2%
In order to define the $keyword1 and $keyword2 variables you can do something like:
list($keyword1, $keyword2) = explode(' ', $_GET['keyword']);
or you can simply use "%" . implode('%', explode(' ', $_GET['keyword'])) . "%" in case you have multiple possible keywords
There is a two way
one is hard way doing by php and mysql
$keyword = $_GET('keyword');
$keywordArray = explode(" ",$keyword);
$queryString = "";
foreach($keywordArray as $key=>$value) {
$queryString .= " column_name LIKE '%$value%' OR";
}
"SElECT * FROM table WHERE ".$queryString
second is mysql itself, that is Full text search

Grouping in a list - php

I have mysql result as you can see below. I want to make shop based list, how can I do in PHP?
SELECT shsv.shop_id, sv.shop, shsv.shop_product_id, shsv.shop_product, sum(shsv.cash)
FROM turerp_db.shop_has_sale_view shsv
left JOIN shop_view sv ON ( sv.shop_id = shsv.shop_id )
group by shsv.shop_id, shsv.shop_product_id
ID SHOP P_ID PRODUCT PRICE
10 SHOP_1 14 PRODUCT_1 322
11 SHOP_2 3 PRODUCT_2 2000
11 SHOP_2 5 PRODUCT_3 55
SHOP_1
PRODUCT_1
SHOP_2
PRODUCT_2
PRODUCT_3
You can use the power of associative nature of PHP arrays: http://www.php.net/manual/en/language.types.array.php
$shops = [];
$shops['SHOP_1'][] = 'PRODUCT_1';
$shops['SHOP_2'][] = 'PRODUCT_2';
$shops['SHOP_2'][] = 'PRODUCT_3';
var_dump($shops) will print:
array(2) {
["SHOP_1"]=>
array(1) {
[0]=>
string(9) "PRODUCT_1"
}
["SHOP_2"]=>
array(2) {
[0]=>
string(9) "PRODUCT_2"
[1]=>
string(9) "PRODUCT_3"
}
}
You should also refer to your mysql driver documentation. It is likely that some of its methods will return your data in a similar manner.
try this
$sql = mysql_query("SELECT * FROM tablename ORDER BY SHOP P_ID ASC");//your query
$cat = ""; //initialize $cat variable
while($row = mysql_fetch_assoc($sql)){
if($row['SHOP P_ID '] != $cat) echo "<h3>".$row['SHOP P_ID ']."</h3>\r\n";
echo "<p>".$row['PRODUCT']."</p>\r\n";
$cat = $row['SHOP P_ID'];
}
I have found solution myself, if you have better solution, please share us.
$query = $this -> db -> query('SELECT shsv.shop_id, sv.shop, shsv.shop_product_id, shsv.shop_product, sum(shsv.cash) AS cash_total FROM turerp_db.shop_has_sale_view shsv left JOIN shop_view sv ON ( sv.shop_id = shsv.shop_id ) group by shsv.shop_id, shsv.shop_product_id');
$shops= $query -> result();
$count = 0;
echo '<table>';
foreach ($shops as $shop) {
if($count == 0){
echo '<thead><tr><th colspan="2">'.$shop->shop.'</th></tr></thead>';
echo '<tbody>';
echo '<tr><td>'.$shop->shop_product.'</td><td>'.$shop->cash_total.'</td></tr>';
$shop_id = $shop -> shop_id;
}
else {
if($shop_id == $shop -> shop_id){
echo '<tr><td>'.$shop->shop_product.'</td><td>'.$shop->cash_total.'</td></tr>';
}
else {
echo '</tbody>';
echo '<thead><tr><th colspan="2">'.$shop->shop.'</th></tr></thead>';
echo '<tbody>';
echo '<tr><td>'.$shop->shop_product.'</td><td>'.$shop->cash_total.'</td></tr>';
}
$shop_id = $shop -> shop_id;
}
$count++;
}
echo '</tbody>';
echo '</table>';

Issues with Pulling data from SQL

My script was working no problems until i added in a third element into my database:
sysinfo
SysInfoID CHNo Module Dector GasDetected ServiceID SiteID
1 1 O2 O2 O2 0 1
2 2 Meth Meth Meth 0 1
3 4 O2 O2 O2 0 1
php script
$data = mysql_query("SELECT j.JobID, j.CompletedBy, u.NameUser, j.SchDate, cu.CustName,
j.ContractNo, j.VisitNo, s.EqName, si.SiteName, si.SiteContact,
si.SiteAddress,si.SiteCounty, si.SiteTele, j.SiteID, si.SiteEmail, cu.CustEmail
FROM jobs as j
INNER JOIN users as u
ON j.AssignedTo = u.UserID
INNER JOIN site as si
ON j.SiteID = si.SiteID
INNER JOIN customer as cu
ON j.custID = cu.custID
INNER JOIN systypes as s
ON j.SysTypeID = s.SysTypeID
WHERE j.CompletedBy ='0'
AND j.AssignedTo='$mytechname'")
or die(mysql_error());
$count = mysql_num_rows($data);
$CHNo = array();
$Location = array();
$Module = array();
$Dector = array();
$GasDetected = array();
echo "<ul id='jlisthead' data-role='listview' data-inset='true' data-theme='a'><li data-role='list-divider'>Available Jobs ($count)</li></ul>";
echo '<ul data-role="listview" id="jobslist" data-split-icon="plus" data-theme="a" data-split-theme="b" data-inset="true" style="overflow: auto; height:175px; max-height: 175px;">';
while( $info = mysql_fetch_array ($data))
{
if($info[7] == '8' || $info[7] == '9'){
echo "<li><a id='ajob' data-id='$info[0]' data-assignedto='$info[2]' data-schdate='$info[3]' data-contractno='$info[5]' data-visitno='$info[6]' data-systype='$info[7]' data-sitename='$info[8]' data-contact='$info[9]' data-address='$info[10]' data-county='$info[11]' data-sitetel='$info[12]' data-siteid='$info[13]' data-siteemail='$info[14]' data-custemail='$info[15]' href='#'>$info[8]</a><a id='add' data-aid='$info[0]' data-aassignedto='$info[2]' data-aschdate='$info[3]' data-acontractno='$info[5]' data-avisitno='$info[6]' data-asystype='$info[7]' data-asitename='$info[8]' data-acontact='$info[9]' data-aaddress='$info[10]' data-acounty='$info[11]' data-asitetel='$info[12]' data-asiteid='$info[13]' data-asiteemail='$info[14]' data-acustemail='$info[15]'></a></li>";
}
else{
$data2 = mysql_query("SELECT SysInfoID, CHNo, Location, Module, Dector, GasDetected
FROM systeminfo
WHERE SiteID = $info[13]")
or die(mysql_error());
$arrlength=mysql_num_rows($data2);
while( $info2 = mysql_fetch_array ($data2)){
for($k =0;$k<$arrlength;$k++){
$CHNo[$k] = $info2[1];
$Location[$k] = $info2[2];
$Module[$k] = $info2[3];
$Dector[$k] = $info2[4];
$GasDetected[$k] = $info2[5];
}
}
$dis = "<li><a id='ajob' data-id='$info[0]' data-assignedto='$info[2]' data-schdate='$info[3]' data-contractno='$info[5]' data-visitno='$info[6]' data-systype='$info[7]' data-sitename='$info[8]' data-contact='$info[9]' data-address='$info[10]' data-county='$info[11]' data-sitetel='$info[12]' data-siteid='$info[13]' data-siteemail='$info[14]' data-custemail='$info[15]' href='#'>$info[8]</a><a id='add' data-aid='$info[0]' data-aassignedto='$info[2]' data-aschdate='$info[3]' data-acontractno='$info[5]' data-avisitno='$info[6]' data-asystype='$info[7]' data-asitename='$info[8]' data-acontact='$info[9]' data-aaddress='$info[10]' data-acounty='$info[11]' data-asitetel='$info[12]' data-asiteid='$info[13]' data-asiteemail='$info[14]' data-acustemail='$info[15]' ";
for($j = 0;$j<$arrlength;$j++){
$dis .= "data-achno".$j." ='$CHNo[$j]' data-alocation".$j."='$Location[$j]' data-amodule".$j."='$Module[$j]' data-adector".$j."='$Dector[$j]' data-agasdetected".$j."='$GasDetected[$j]'";
}
$dis .= "data-achtotal='$arrlength'></a></li>";
echo $dis;
}
}
echo '</ul>';
To explain a little, I want to check to see if the $info[7] element is 8/9 if it is then print out the information in a list. if its not then go do an ADDITIONAL query to get more information from another table (sysinfo) and store multipliable values within my list using the attr data.
The first query i have no issues with, but its when i go to do the additional query thats were it gets messed up. my arrlength is equal to "3" but all the data within the data-attr is the same.
example
<a id="add" data-aid="1" data-aassignedto="Mark McGuinness" data-aschdate="2014-03-22" data-acontractno="12" data-avisitno="4" data-asystype="3500" data-asitename="Tesco" data-acontact="Ann Jones" data-aaddress="21 Good Street Glasgow G14 4CA" data-acounty="Strathcylde" data-asitetel="1413216545" data-asiteid="1" data-asiteemail="" data-acustemail="admin#tesco.com"
data-achno0="3" data-alocation0="Side door" data-amodule0="02" data-adector0="02" data-agasdetected0="02"
data-achno1="3" data-alocation1="Side door" data-amodule1="02" data-adector1="02" data-agasdetected1="02"
data-achno2="3" data-alocation2="Side door" data-amodule2="02" data-adector2="02" data-agasdetected2="02" data-achtotal="3" title="" class="ui-btn ui-btn-icon-notext ui-icon-plus ui-btn-b"></a>
Please help it was working before i inserted a new row into the database. Thanks in advance.
Resolved
removed the for loop within the while loop:
previous
while( $info2 = mysql_fetch_array ($data2)){
for($k =0;$k<$arrlength;$k++){
$CHNo[$k] = $info2[1];
$Location[$k] = $info2[2];
$Module[$k] = $info2[3];
$Dector[$k] = $info2[4];
$GasDetected[$k] = $info2[5];
}
}
!!!Fix!!!!
while( $info2 = mysql_fetch_array ($data2)){
$CHNo[$k] = $info2[1];
$Location[$k] = $info2[2];
$Module[$k] = $info2[3];
$Dector[$k] = $info2[4];
$GasDetected[$k] = $info2[5];
$k++;
}

Sort PHP - 2 columns with common subheaders

My code does the two columns, like this:
neighborhood 1
restaurant 1
neighborhood 1
restaurant 2
neighborhood 1
restaurant 3
I WANT:
neighborhood 1
restaurant 1
restaurant 2
restaurant 3
$result = mysql_query("SELECT ID,RName,NHood FROM Restaurants ORDER BY NHood ASC, TRIM(LEADING 'The ' FROM RName) ASC",$connect);
$numRows = mysql_num_rows($result);
$middleIndex = (int)(($numRows+1) / 2);
$names = array();
while($row = mysql_fetch_assoc($result)) {
$names[] = $row['RName'];
$id[] = $row['ID'];
$hood[] = $row['NHood'];
}
// print the left column
echo "<table>";
echo "<tr>";
echo "<td width=60%>";
echo "<div id=\"left\">\n";
for($i = 0; $i < $middleIndex; $i++) {
echo $hood[$i];
echo "<p>$names[$i]</p>\n";
}
echo "</div>\n";
echo "</td>";
// print the right column
echo "<td>";
echo "<div id=\"right\">\n";
for($i = $middleIndex; $i < $numRows; $i++) {
echo $hood[$i];
echo "<p>$names[$i]</p>\n";
}
echo "</div>\n";
echo "</tr>";
echo "</table>";
Here's the logic you want (pseduocode):
SELECT
ID,
RName,
NHood
FROM
Restaurants
ORDER BY
NHood ASC, RName ASC
This should return a list of results ordered first by the neighborhood, then by restaurant name.
Next, you'll process those results line-by-line to create a nested array with the data structure you want for your view:
$neighborhoods = array();
foreach($result as $row)
{
// Add each restaurant to a list named for the current neighborhood
$neighborhoods[$row['NHood']][] = $row['RName'];
}
This will produce a data structure like this:
$neighborhoods = array(
'neighborhood1' => array(
'restaurant1',
'restaurant2',
'restaurant3',
),
'neighborhood2' => array(
'restaurant1',
'restaurant2',
),
)
Which you will then use by doing this:
foreach($neighborhoods as $neighborhood => $restaurants)
{
echo $neighborhood;
foreach($restaurants as $restaurant)
{
echo $restaurant;
}
}
If your list is really large and you're worried about memory the implementation is a bit different but the logic is the same. This technique is faster but it's a bit harder to read and maintain because presentation and data layer logic are all mixed together:
$currentNH = null;
while($row = fetch_row($results))
{
// Detect when the neighborhood changes
if($currentNH != $row['NHood']) {
echo $row['NHood'];
}
echo $row['RName'];
}

Grouping items in a foreach loop in PHP

So, I'm trying to make a sort of user-market type thing. There's a database with item_names, basically describes the virtual items, then there's another table market, where when a user lists one of their items, it's put for sale on the user-user market.
My only problem here is I want to group it by item name, referenced in the item_name table. I know I could do a bunch of if/else statements but that's extraneous not only because there's a lot of items, but also because I will add more items as time goes on. I want the end result to be something like
--[Water for sale]---------------------+
[50 water for sale] [20 water for sale]
[10 water for sale] [10 water for sale]
--[Chips for sale]----------------------+
[50 chips for sale] [20 chips for sale]
[10 chips for sale] [10 chips for sale]
And so on, done dynamically.
Any help?
Fetch data:
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$itemName = $row["item_name"];
if (!array_key_exists($itemName, $data)) {
$data[$itemName] = array();
}
$data[$itemName][] = $row;
}
Display data
foreach ($data as $itemName => $rows) {
echo '<h1>', $itemName, '</h1>';
echo '<ul>';
foreach ($rows as $row) {
echo '<li>', $row["article_name"], '</li>';
}
echo '</ul>';
}
Make sure you order (not group) the results on your SQL query, then the loop will be very simple (assuming PDO, and a column item_name on table item_names):
$sth = $dbh->query ("SELECT * FROM item_names ORDER BY item_name");
$lastname = '';
while ($row = $sth->fetch()) {
if($lastname != $row['item_name']) {
echo '<h1>' . $row['item_name'] . '</h1>';
}
// echo contents for each item here
// remember name from last row
$lastname = $row['item_name'];
}

Categories