I have two tables, dishes and days_avail, where dishes contains information regarding dishes cooked and days_avail contains what days a certain dish is available.
days_avail looks like this:
daysid || dishid || monday || tuesday || wednesday || friday
daysid: unique id
dishid: dish id from dishes table
Mon - Fri: boolean
So, what I am able to do is pull the dishes and show relevant info along with what day it is available on. However, what I am trying to accomplish is categorizing the dishes by the days they are available. So something like this:
Monday
dish name
dish desc desc desc
Tuesday
Dish name
dish desc dish desc
My query is as follows:
$sql = "SELECT * FROM dishes JOIN days_avail ON days_avail.dishid = dishes.id WHERE user_id = :cookid ORDER BY days_avail.daysid";
try {
$stmt = $db->prepare($sql);
$stmt->execute(array(
':cookid' => $cookid
));
}
catch(Exception $error) {
echo '<p class="bg-danger">', $error->getMessage(), '</p>';
}
while($row = $stmt->fetch()) {
$dish_name = $row['dish_name'];
$dish_desc = $row['dish_desc'];
$dish_price = $row['dish_price'];
$mon = $row['Monday'];
$tues = $row['Tuesday'];
$wed = $row['Wednesday'];
$thurs = $row['Thursday'];
$fri = $row['Friday'];
}
I can't group the dishes under one day its available. I have tried using a if statement (example: if($mon == 1) { echo "Monday // dish_info, etc" }) but this results in the heading being repeated for each dish.
I have also tried using java handlebars to more or less run a query and then simply "stuff" the results in the (appropriate) div boxes but did not work.
I am get a complete lost here. I would greatly appreciate any help.
Thank you
You can do this by putting your returned rows into an array, based off the day available-
...your query code...
$days=array('Monday'=>array(),'Tuesday'=>array(),'Wednesday'=>array(),'Thursday'=>array(),'Friday'=>array());
while($row = $stmt->fetch()) {
foreach($days as $day=>$array){
if($row[$day]){
$days[$day][]=array('dish_name'=>$row['dish_name'],
'dish_desc'=>$row['dish_desc'],
'dish_price'=>$row['dish_price']);
}
}
}
now just loop over your $days array
foreach($days as $day => $dishes){
echo "<h2>$day</h2>";
foreach($dishes as $dish){
echo $dish['dish_name']."<br />";
echo $dish['dish_desc']."<br />";
echo $dish['dish_price']."<br />";
}
}
Try this :)
$sql = "SELECT * FROM dishes JOIN days_avail ON days_avail.dishid = dishes.id WHERE user_id = :cookid ORDER BY days_avail.daysid";
try {
$stmt = $db->prepare($sql);
$stmt->execute(array(
':cookid' => $cookid
));
}
catch(Exception $error) {
echo '<p class="bg-danger">', $error->getMessage(), '</p>';
}
$dishes = array(
'mon' = array(),
'tues' = array(),
'wed' = array(),
'thurs' = array(),
'fri' = array()
);
while ($row = $stmt->fetch()) {
$dish = array(
'name' => $row['dish_name'],
'desc' => $row['dish_desc'],
'price' => $row['dish_price']
);
$mon = (bool) $row['Monday'];
$tues = (bool) $row['Tuesday'];
$wed = (bool) $row['Wednesday'];
$thurs = (bool) $row['Thursday'];
$fri = (bool) $row['Friday'];
if ($mon) {
$dishes['mon'][] = $dish;
}
if ($tues) {
$dishes['tues'][] = $dish;
}
if ($wed) {
$dishes['wed'][] = $dish;
}
if ($thurs) {
$dishes['thurs'][] = $dish;
}
if ($fri) {
$dishes['fri'][] = $dish;
}
}
// iterate over Monday dishes
foreach ($dishes['mon'] as $dish) {
// $dish['name'], $dish['desc'], $dish['price']
}
// and so on....
Related
I'm having hard time with this issue
I have multiple queries some data appear in other results...
$query = "SELECT * FROM `hotels`";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0) {
while($row=mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$queryPhotos="SELECT * FROM hotel_photo WHERE hotel_id = ".$row['id']." ";
$resultPhotos=mysqli_query($connect,$queryPhotos);
while($rowPhotos=mysqli_fetch_assoc($resultPhotos)) {
$photos[] = array(
"imgUrl" => $rowPhotos['img_url'],
"hotel_id" => $rowPhotos['hotel_id']
);
}
$apiResult[] = array(
'hotel_name' => $hotelname,
'hotel_photos' => $photos,
);
}
header('Content-type: application/json');
echo json_encode($apiResult, JSON_NUMERIC_CHECK);
}
This is my hotel database
and my hotel_photos database
Why I'm still seeing 'hotel_id 1' in dubai hotel...?
Thank you so much for your help.
You aren't empting the $photos array in every new iteration for a new hotel. Hence, the previous results also exists in the array. You need to fix as below:
<?php
while($row = mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$photos = []; // add this line
I'm running through some distinct user ID's (about 147 of them, retrieved from a table with many duplicates) with a foreach loop and then when retrieved, using them to retrieve more user details. I then place these details within an array in order to push them to my JavaScript.
For some reason the result that I get from the array is what seems to be an infinite loop that has quit somewhere in the process.
Here's an example:
This is the code that I am currently running:
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
else
{
continue;
}
echo json_encode($past_threshold_users);
}
//echo json_encode($results);
wp_die();
}
Try this code
I have move this echo json_encode($past_threshold_users); code after foreach loop.
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
/*else
{
continue;
} */
}
echo json_encode($past_threshold_users);
//echo json_encode($results);
wp_die();
}
i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.
I have two tables sport_tbl, match_tbl. In sport_tbl, i defined sport_name such as cricket. In match_tbl, I have match_name,match_date,sport_id.
I want to show match_date of every sport_name (ex. i am showing match_date list for cricket sport and i want to show every date has match_name list).
I want to show one distinct match_date.
Image
my controller code:-
$url = 'cricket' // for example first sport_name
$data['getSportMatch'] = $this->user_model->getSportMatch($url);
my model code:-
public function getSportMatch($sport)
{
$query = $this->db->get_where('match_tbl',array('sport_name' => $sport));
if($query->num_rows > 0)
{
foreach($query->result() as $item){
$data[] = $item;
}
return $data;
}
}
my code in view:-
<div><?php foreach($getSport as $item): ?><h4><?= $item->sport_name; ?></h4><div><?= foreach($getSportMatch as $item): ?>
match_date)) ?>here i want to show list match_name of every match_date
My table structure images
1) sport_tbl
2) match_tbl
3) another match_tbl
you can solve this in model easily. if i did not understand wrong . you need 2 function in model.
1. will get sport names
2. will get matches of given sport name
//model functions
function get_sports(){
$data = array();
$sports = $this->db->select('sport_name')->from('sport_tbl')->get()->result();
if($sports)
{
foreach($sports as $sport){
$data[$sport->sport_name] = $this->get_matches($sport->sport_name);
}
return $data;
}
}
function get_matches($sport_name){
$matches = $this->db->select('*')->from('match_tbl')->where('sport_name',$sport_name)->get()->result();
return $matches;
}
so in view data will be something like this
$data => array(
'cricket'=> array(0 => array(
'match_id' => 11,
'sport_id' = 2 .....
)))
Try this coding ...
public function getSportMatch($sport)
{
$query = $this->db->query("SELECT * FROM sport_tbl as st INNER JOIN match_tbl as mt ON st.sport_id = mt.sport_id WHERE st.sport_name ='".$sport."'");
if($query->num_rows > 0)
{
$query_result = $query->result_array();
$final_result = array();
foreach($query_result as $result ) {
$date = $result['match_date'];
$final_result[$date][] = $result;
}
return $final_result;
}
}
View Coding :-
if(isset($final_result)) {
foreach($final_result as $result) {
echo $result['match_date']; // First display match date
if(isset($result['match_date'])) {
foreach($result['match_date'] as $match) {
echo $match['match_name']; // Second listout the match name
}
}
}
}
I try to write this code on few ways, but always the result is good only for first team all other results are bad.
When I put id of some other club instead of $id I get the good result for that team but than is only one row, I want to show all 20 teams.
<table>
<thead><tr><th>Name</th><th>Played</th><th>0,5</th><th>1,5</th><th>2,5</th>
<th>3,5</th><th>4,5</th></tr></thead>
<tbody>
<?php
$teams = mysql_query("select * from teams");
$num_teams = mysql_num_rows($teams);
while ($group = mysql_fetch_row($teams)) {
$id_team[] = $group;
}
for ($a = 0; $a < $num_teams; $a++) {
if (isset($num_array)) {
mysql_data_seek($query_array, 0 );
$search_array_over = array();
}
$id = $id_team[$a][0];
$name_over = $id_team[$a][1];
$query_array = mysql_query("select * from full_stat where kl1 = $id or kl2 = $id");
$num_array = mysql_num_rows($query_array);
while ($row = mysql_fetch_row($query_array)) {
$data_over[] = $row;
}
$search_array_over = array('1' => '0', '2' => '0' ,'3' => '0', '4' => '0','5' => '0','6' => '0');
for ($now = 0;$now < $num_array; $now++) {
$over_pass = ($data_over[$now][3] + $data_over[$now][4]);
for ($pass = 1; $pass < 7; $pass++) {
if ($over_pass >= $pass) {
$final_pass = $pass;
}
else {
$final_pass = '6';
}
if (array_key_exists($final_pass, $search_array_over)) {
$search_array_over[$final_pass] += 1;
}
else {
$search_array_over[$final_pass] = 1;
}
}
}
echo '<tr><td>'.$name_over.'</td><td>'.$num_array.'</td> <td>'.$search_array_over[1].'</td><td>'.$search_array_over[2].'</td><td>'.$search_array_over[3].'</td><td>'.$search_array_over[4].'</td><td>'.$search_array_over[5].'</td></tr>';
}
?>
</tbody>
</table>
That is one confusing block of PHP code.
A better explanation of your final output would probably help here, but I'm going to guess it's the teamlist plus their statistics.
Since dissecting your current code strikes me as painful, I'm going to describe how I would do this instead.
In your database you have 2 tables, "team" and "team_stats"
Team Structure:
id int
name varchar
....
Stats Structure:
team_id int
someStat int
otherStat int
....
$stmt = $mysqli -> prepare("SELECT * FROM team LEFT JOIN team_stats ON team_stats.team_id");
$stmt -> execute();
$result = $stmt -> fetch_all();
foreach($result as $team) {
// output data to page
}
?>