Codeigniter single data extraction error with result - php

I've done a live search section with ajax, but when I combine the pictures and products table with join, the number of pictures shows as many products as I want to show this one. Codeigniter just started to confuse me a bit thanks for your help
Model
public function search_products($search)
{
$search = remove_special_characters($search);
$this->db->join('products', 'images.product_id = products.id');
$this->db->like('products.title', $search);
$this->db->order_by('products.is_promoted', 'DESC');
$this->db->limit(8);
$query = $this->db->get('images');
return $query->result();
}
Controller
public function ajax_search()
{
$lang_base_url = $this->input->post('lang_base_url', true);
$search_type = $this->input->post('search_type', true);
$input_value = $this->input->post('input_value', true);
$input_value = remove_special_characters($input_value);
$data = array(
'result' => 0,
'response' => ''
);
if (!empty($search_type) && !empty($input_value)) {
if ($search_type == 'member') {
$data['result'] = 1;
$response = '<ul>';
$members = $this->profile_model->search_members_limited($input_value);
if (!empty($members)) {
foreach ($members as $member) {
$response .= '<li>' . $member->username . '</li>';
}
} else {
$response .= '<li>' . $input_value . '</li>';
}
$response .= '</ul>';
$data['response'] = $response;
} else {
$data['result'] = 1;
$response = '<div class="suggestions__group-content">';
$products = $this->product_model->search_products($input_value);
if (!empty($products)) {
$response .= '<div style="margin-top: 5px;" class="suggestions__group-title">Arama Sonucu</div>';
foreach ($products as $product) {
$response .='
<a class="suggestions__item suggestions__product" href="' . $lang_base_url . $product->slug . '">
<div class="suggestions__product-image"><img width="40"
src="' .base_url("uploads/images/".$product->image_small) . '" alt="' . $product->title . '"></div>
<div class="suggestions__product-info">
<div class="suggestions__product-name">' . $product->title . '</div>
<div class="suggestions__product-rating">
<div class="suggestions__product-rating-label">Uygun Fiyatları Görmek İçin İnceleyin </div>
</div>
</div>
<div style="margin-right: 10px;" class="suggestions__product-price">'.fiyatsay($product->id).' Fiyat Bulundu</div>
</a>
';
}
} else {
$response .= '<div style="margin-top: 5px;" class="suggestions__group-title">Arama Sonucu</div>';
$response .= '<div class="suggestions__group-content"><a class="suggestions__item suggestions__category" href="' . $lang_base_url . 'products?search=' . $input_value . '">' . $input_value . '</a></div>';
}
$response .= '</div>';
$data['response'] = $response;
}
}
echo json_encode($data);
}
Result
How can I do? Thanks in advance!

I found the solution :)
$this->db->group_by('images.product_id');
public function search_products($search)
{
$search = remove_special_characters($search);
$this->db->join('products', 'products.id = images.product_id');
$this->db->like('products.title', $search);
$this->db->group_by('images.product_id');
$this->db->order_by('products.is_promoted', 'DESC');
$this->db->limit(8);
$query = $this->db->get('images');
return $query->result();
}

Related

Wrap laravel query inside cache::remember

I want to wrap my laravel query inside the cache::remember() method which is not big problem. My problem with it is that my query first calls the function from the controller and there is a file transaction.php in this file. I'm getting this function called and after it, I'm putting some where() conditions on this function return query at the end. The final query gives results, and I'm passing this into the Yajra datatable.
So in short, my query is not on the same file so that i can wrap inside the cache::remember() function.
How can I wrap my query, which is placed in two files, controller and transaction.php. I hope you understand.
Here is a function inside the controller:
public function index()
{
$is_admin = $this->businessUtil->is_admin(auth()->user());
if ( !$is_admin && !auth()->user()->hasAnyPermission(['sell.view', 'sell.create', 'direct_sell.access', 'direct_sell.view', 'view_own_sell_only', 'view_commission_agent_sell', 'access_shipping', 'access_own_shipping', 'access_commission_agent_shipping', 'so.view_all', 'so.view_own']) ) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
$is_woocommerce = $this->moduleUtil->isModuleInstalled('Woocommerce');
$is_tables_enabled = $this->transactionUtil->isModuleEnabled('tables');
$is_service_staff_enabled = $this->transactionUtil->isModuleEnabled('service_staff');
$is_types_service_enabled = $this->moduleUtil->isModuleEnabled('types_of_service');
if (request()->ajax()) {
$payment_types = $this->transactionUtil->payment_types(null, true, $business_id);
$with = [];
$shipping_statuses = $this->transactionUtil->shipping_statuses();
$sale_type = !empty(request()->input('sale_type')) ? request()->input('sale_type') : 'sell';
$sells = $this->transactionUtil->getListSells($business_id, $sale_type, request()->customer_id);
$permitted_locations = auth()->user()->permitted_locations();
if ($permitted_locations != 'all') {
$sells->whereIn('transactions.location_id', $permitted_locations);
}
//Add condition for created_by,used in sales representative sales report
if (request()->has('created_by')) {
$created_by = request()->get('created_by');
if (!empty($created_by)) {
$sells->where('transactions.created_by', $created_by);
}
}
$partial_permissions = ['view_own_sell_only', 'view_commission_agent_sell', 'access_own_shipping', 'access_commission_agent_shipping'];
if (!auth()->user()->can('direct_sell.access')) {
$sells->where( function($q){
if (auth()->user()->hasAnyPermission(['view_own_sell_only', 'access_own_shipping'])) {
$q->where('transactions.created_by', request()->session()->get('user.id'));
}
//if user is commission agent display only assigned sells
if (auth()->user()->hasAnyPermission(['view_commission_agent_sell', 'access_commission_agent_shipping'])) {
$q->orWhere('transactions.commission_agent', request()->session()->get('user.id'));
}
});
}
if (!empty(request()->input('payment_status')) && request()->input('payment_status') != 'overdue') {
$sells->where('transactions.payment_status', request()->input('payment_status'));
} elseif (request()->input('payment_status') == 'overdue') {
$sells->whereIn('transactions.payment_status', ['due', 'partial'])
->whereNotNull('transactions.pay_term_number')
->whereNotNull('transactions.pay_term_type')
->whereRaw("IF(transactions.pay_term_type='days', DATE_ADD(transactions.transaction_date, INTERVAL transactions.pay_term_number DAY) < CURDATE(), DATE_ADD(transactions.transaction_date, INTERVAL transactions.pay_term_number MONTH) < CURDATE())");
}
//Add condition for location,used in sales representative expense report
if (request()->has('location_id')) {
$location_id = request()->get('location_id');
if (!empty($location_id)) {
$sells->where('transactions.location_id', $location_id);
}
}
if (!empty(request()->input('rewards_only')) && request()->input('rewards_only') == true) {
$sells->where(function ($q) {
$q->whereNotNull('transactions.rp_earned')
->orWhere('transactions.rp_redeemed', '>', 0);
});
}
if (!empty(request()->customer_id)) {
$customer_id = request()->customer_id;
$sells->where('contacts.id', $customer_id);
}
if (!empty(request()->start_date) && !empty(request()->end_date)) {
$start = request()->start_date;
$end = request()->end_date;
$sells->whereDate('transactions.transaction_date', '>=', $start)
->whereDate('transactions.transaction_date', '<=', $end);
}
//Check is_direct sell
if (request()->has('is_direct_sale')) {
$is_direct_sale = request()->is_direct_sale;
if ($is_direct_sale == 0) {
$sells->where('transactions.is_direct_sale', 0);
$sells->whereNull('transactions.sub_type');
}
}
//Add condition for commission_agent,used in sales representative sales with commission report
if (request()->has('commission_agent')) {
$commission_agent = request()->get('commission_agent');
if (!empty($commission_agent)) {
$sells->where('transactions.commission_agent', $commission_agent);
}
}
if ($is_woocommerce) {
$sells->addSelect('transactions.woocommerce_order_id');
if (request()->only_woocommerce_sells) {
$sells->whereNotNull('transactions.woocommerce_order_id');
}
}
if (request()->only_subscriptions) {
$sells->where(function ($q) {
$q->whereNotNull('transactions.recur_parent_id')
->orWhere('transactions.is_recurring', 1);
});
}
if (!empty(request()->list_for) && request()->list_for == 'service_staff_report') {
$sells->whereNotNull('transactions.res_waiter_id');
}
if (!empty(request()->res_waiter_id)) {
$sells->where('transactions.res_waiter_id', request()->res_waiter_id);
}
if (!empty(request()->input('sub_type'))) {
$sells->where('transactions.sub_type', request()->input('sub_type'));
}
if (!empty(request()->input('created_by'))) {
$sells->where('transactions.created_by', request()->input('created_by'));
}
if (!empty(request()->input('status'))) {
$sells->where('transactions.status', request()->input('status'));
}
if (!empty(request()->input('sales_cmsn_agnt'))) {
$sells->where('transactions.commission_agent', request()->input('sales_cmsn_agnt'));
}
if (!empty(request()->input('service_staffs'))) {
$sells->where('transactions.res_waiter_id', request()->input('service_staffs'));
}
$only_shipments = request()->only_shipments == 'true' ? true : false;
if ($only_shipments) {
$sells->whereNotNull('transactions.shipping_status');
}
if (!empty(request()->input('shipping_status'))) {
$sells->where('transactions.shipping_status', request()->input('shipping_status'));
}
if (!empty(request()->input('for_dashboard_sales_order'))) {
$sells->whereIn('transactions.status', ['partial', 'ordered'])
->orHavingRaw('so_qty_remaining > 0');
}
if ($sale_type == 'sales_order') {
if (!auth()->user()->can('so.view_all') && auth()->user()->can('so.view_own')) {
$sells->where('transactions.created_by', request()->session()->get('user.id'));
}
}
if (empty(request()->customer_id)) {
$sells->groupBy('transactions.id');
}
if (!empty(request()->suspended)) {
$transaction_sub_type = request()->get('transaction_sub_type');
if (!empty($transaction_sub_type)) {
$sells->where('transactions.sub_type', $transaction_sub_type);
} else {
$sells->where('transactions.sub_type', null);
}
$with = ['sell_lines'];
if ($is_tables_enabled) {
$with[] = 'table';
}
if ($is_service_staff_enabled) {
$with[] = 'service_staff';
}
$sales = $sells->where('transactions.is_suspend', 1)
->with($with)
->addSelect('transactions.is_suspend', 'transactions.res_table_id', 'transactions.res_waiter_id', 'transactions.additional_notes')
->get();
return view('sale_pos.partials.suspended_sales_modal')->with(compact('sales', 'is_tables_enabled', 'is_service_staff_enabled', 'transaction_sub_type'));
}
$with[] = 'payment_lines';
if (!empty($with)) {
$sells->with($with);
}
//$business_details = $this->businessUtil->getDetails($business_id);
if ($this->businessUtil->isModuleEnabled('subscription')) {
$sells->addSelect('transactions.is_recurring', 'transactions.recur_parent_id');
}
$sales_order_statuses = Transaction::sales_order_statuses();
$datatable = Datatables::of($sells)
->addColumn(
'action',
function ($row) use ($only_shipments, $is_admin, $sale_type) {
$html = '<div class="btn-group">
<button type="button" class="btn btn-info dropdown-toggle btn-xs"
data-toggle="dropdown" aria-expanded="false">' .
__("messages.actions") .
'<span class="caret"></span><span class="sr-only">Toggle Dropdown
</span>
</button>
<ul class="dropdown-menu dropdown-menu-left" role="menu">' ;
if (auth()->user()->can("sell.view") || auth()->user()->can("direct_sell.view") || auth()->user()->can("view_own_sell_only")) {
$html .= '<li><i class="fas fa-eye" aria-hidden="true"></i> ' . __("messages.view") . '</li>';
}
if (!$only_shipments) {
if ($row->is_direct_sale == 0) {
if (auth()->user()->can("sell.update")) {
$html .= '<li><a target="_blank" href="' . action('SellPosController#edit', [$row->id]) . '"><i class="fas fa-edit"></i> ' . __("messages.edit") . '</a></li>';
}
} elseif ($row->type == 'sales_order') {
if (auth()->user()->can("so.update")) {
$html .= '<li><a target="_blank" href="' . action('SellController#edit', [$row->id]) . '"><i class="fas fa-edit"></i> ' . __("messages.edit") . '</a></li>';
}
} else {
if (auth()->user()->can("direct_sell.update")) {
$html .= '<li><a target="_blank" href="' . action('SellController#edit', [$row->id]) . '"><i class="fas fa-edit"></i> ' . __("messages.edit") . '</a></li>';
}
}
$delete_link = '<li><i class="fas fa-trash"></i> ' . __("messages.delete") . '</li>';
if ($row->is_direct_sale == 0) {
if (auth()->user()->can("sell.delete")) {
$html .= $delete_link;
}
} elseif ($row->type == 'sales_order') {
if (auth()->user()->can("so.delete")) {
$html .= $delete_link;
}
} else {
if (auth()->user()->can("direct_sell.delete")) {
$html .= $delete_link;
}
}
}
if (config('constants.enable_download_pdf') && auth()->user()->can("print_invoice") && $sale_type != 'sales_order') {
$html .= '<li><i class="fas fa-print" aria-hidden="true"></i> ' . __("lang_v1.download_pdf") . '</li>';
if (!empty($row->shipping_status)) {
$html .= '<li><i class="fas fa-print" aria-hidden="true"></i> ' . __("lang_v1.download_paking_pdf") . '</li>';
}
}
if (auth()->user()->can("sell.view") || auth()->user()->can("direct_sell.access")) {
if (!empty($row->document)) {
$document_name = !empty(explode("_", $row->document, 2)[1]) ? explode("_", $row->document, 2)[1] : $row->document ;
$html .= '<li><i class="fas fa-download" aria-hidden="true"></i>' . __("purchase.download_document") . '</li>';
if (isFileImage($document_name)) {
$html .= '<li><i class="fas fa-image" aria-hidden="true"></i>' . __("lang_v1.view_document") . '</li>';
}
}
}
if ($is_admin || auth()->user()->hasAnyPermission(['access_shipping', 'access_own_shipping', 'access_commission_agent_shipping']) ) {
$html .= '<li><i class="fas fa-truck" aria-hidden="true"></i>' . __("lang_v1.edit_shipping") . '</li>';
}
if ($row->type == 'sell') {
if (auth()->user()->can("print_invoice")) {
$html .= '<li><i class="fas fa-print" aria-hidden="true"></i> ' . __("lang_v1.print_invoice") . '</li>
<li><i class="fas fa-file-alt" aria-hidden="true"></i> ' . __("lang_v1.packing_slip") . '</li>';
}
$html .= '<li class="divider"></li>';
if (!$only_shipments) {
if ($row->payment_status != "paid" && auth()->user()->can("sell.payments")) {
$html .= '<li><i class="fas fa-money-bill-alt"></i> ' . __("purchase.add_payment") . '</li>';
}
$html .= '<li><i class="fas fa-money-bill-alt"></i> ' . __("purchase.view_payments") . '</li>';
if (auth()->user()->can("sell.create")) {
$html .= '<li><i class="fas fa-copy"></i> ' . __("lang_v1.duplicate_sell") . '</li>
<li><i class="fas fa-undo"></i> ' . __("lang_v1.sell_return") . '</li>
<li><i class="fas fa-eye"></i> ' . __("lang_v1.view_invoice_url") . '</li>';
}
}
$html .= '<li><i class="fa fa-envelope" aria-hidden="true"></i>' . __("lang_v1.new_sale_notification") . '</li>';
} else {
$html .= '<li><i class="fas fa-paperclip" aria-hidden="true"></i>' . __("lang_v1.shipping_documents") . '</li>';
}
$html .= '</ul></div>';
return $html;
}
)
->removeColumn('id')
->editColumn(
'final_total',
'<span class="final-total" data-orig-value="{{$final_total}}">#format_currency($final_total)</span>'
)
->addColumn('products', function($row){
return $row->product_name;
})
->editColumn(
'unit_price',
'<span class="unit-price" data-orig-value="{{$unit_price}}">#format_currency($unit_price)</span>'
)
->editColumn(
'tax_amount',
'<span class="total-tax" data-orig-value="{{$tax_amount}}">#format_currency($tax_amount)</span>'
)
->editColumn(
'total_paid',
'<span class="total-paid" data-orig-value="{{$total_paid}}">#format_currency($total_paid)</span>'
)
->editColumn(
'total_before_tax',
'<span class="total_before_tax" data-orig-value="{{$total_before_tax}}">#format_currency($total_before_tax)</span>'
)
->editColumn(
'discount_amount',
function ($row) {
$discount = !empty($row->discount_amount) ? $row->discount_amount : 0;
if (!empty($discount) && $row->discount_type == 'percentage') {
$discount = $row->total_before_tax * ($discount / 100);
}
return '<span class="total-discount" data-orig-value="' . $discount . '">' . $this->transactionUtil->num_f($discount, true) . '</span>';
}
)
->editColumn('transaction_date', '{{#format_datetime($transaction_date)}}')
->editColumn(
'payment_status',
function ($row) {
$payment_status = Transaction::getPaymentStatus($row);
return (string) view('sell.partials.payment_status', ['payment_status' => $payment_status, 'id' => $row->id]);
}
)
->editColumn(
'types_of_service_name',
'<span class="service-type-label" data-orig-value="{{$types_of_service_name}}" data-status-name="{{$types_of_service_name}}">{{$types_of_service_name}}</span>'
)
->addColumn('total_remaining', function ($row) {
$total_remaining = $row->final_total - $row->total_paid;
$total_remaining_html = '<span class="payment_due" data-orig-value="' . $total_remaining . '">' . $this->transactionUtil->num_f($total_remaining, true) . '</span>';
return $total_remaining_html;
})
->addColumn('return_due', function ($row) {
$return_due_html = '';
if (!empty($row->return_exists)) {
$return_due = $row->amount_return - $row->return_paid;
$return_due_html .= '<span class="sell_return_due" data-orig-value="' . $return_due . '">' . $this->transactionUtil->num_f($return_due, true) . '</span>';
}
return $return_due_html;
})
->editColumn('invoice_no', function ($row) {
$invoice_no = $row->invoice_no;
if (!empty($row->woocommerce_order_id)) {
$invoice_no .= ' <i class="fab fa-wordpress text-primary no-print" title="' . __('lang_v1.synced_from_woocommerce') . '"></i>';
}
if (!empty($row->return_exists)) {
$invoice_no .= ' <small class="label bg-red label-round no-print" title="' . __('lang_v1.some_qty_returned_from_sell') .'"><i class="fas fa-undo"></i></small>';
}
if (!empty($row->is_recurring)) {
$invoice_no .= ' <small class="label bg-red label-round no-print" title="' . __('lang_v1.subscribed_invoice') .'"><i class="fas fa-recycle"></i></small>';
}
if (!empty($row->recur_parent_id)) {
$invoice_no .= ' <small class="label bg-info label-round no-print" title="' . __('lang_v1.subscription_invoice') .'"><i class="fas fa-recycle"></i></small>';
}
if (!empty($row->is_export)) {
$invoice_no .= '</br><small class="label label-default no-print" title="' . __('lang_v1.export') .'">'.__('lang_v1.export').'</small>';
}
return $invoice_no;
})
->editColumn('shipping_status', function ($row) use ($shipping_statuses) {
$status_color = !empty($this->shipping_status_colors[$row->shipping_status]) ? $this->shipping_status_colors[$row->shipping_status] : 'bg-gray';
$status = !empty($row->shipping_status) ? '<span class="label ' . $status_color .'">' . $shipping_statuses[$row->shipping_status] . '</span>' : '';
return $status;
})
->addColumn('conatct_name', '#if(!empty($supplier_business_name)) {{$supplier_business_name}}, <br> #endif {{$name}}')
->editColumn('quantity', '{{#format_quantity($quantity)}}')
->filterColumn('conatct_name', function ($query, $keyword) {
$query->where( function($q) use($keyword) {
$q->where('contacts.name', 'like', "%{$keyword}%")
->orWhere('contacts.supplier_business_name', 'like', "%{$keyword}%");
});
})
->addColumn('payment_methods', function ($row) use ($payment_types) {
$methods = array_unique($row->payment_lines->pluck('method')->toArray());
$count = count($methods);
$payment_method = '';
if ($count == 1) {
$payment_method = $payment_types[$methods[0]];
} elseif ($count > 1) {
$payment_method = __('lang_v1.checkout_multi_pay');
}
$html = !empty($payment_method) ? '<span class="payment-method" data-orig-value="' . $payment_method . '" data-status-name="' . $payment_method . '">' . $payment_method . '</span>' : '';
return $html;
})
->editColumn('status', function($row) use($sales_order_statuses, $is_admin){
$status = '';
if ($row->type == 'sales_order') {
if ($is_admin && $row->status != 'completed') {
$status = '<span class="edit-so-status label ' . $sales_order_statuses[$row->status]['class'] . '" data-href="'.action("SalesOrderController#getEditSalesOrderStatus", ['id' => $row->id]).'">' . $sales_order_statuses[$row->status]['label'] . '</span>';
} else {
$status = '<span class="label ' . $sales_order_statuses[$row->status]['class'] . '" >' . $sales_order_statuses[$row->status]['label'] . '</span>';
}
}
return $status;
})
->editColumn('so_qty_remaining', '{{#format_quantity($so_qty_remaining)}}')
->setRowAttr([
'data-href' => function ($row) {
if (auth()->user()->can("sell.view") || auth()->user()->can("view_own_sell_only")) {
return action('SellController#show', [$row->id]) ;
} else {
return '';
}
}]);
$rawColumns = ['final_total', 'unit_price', 'action', 'total_paid', 'total_remaining', 'payment_status', 'invoice_no', 'discount_amount', 'tax_amount', 'total_before_tax', 'shipping_status', 'types_of_service_name', 'payment_methods', 'return_due', 'conatct_name', 'status'];
return $datatable->rawColumns($rawColumns)
->make(true);
}
$business_locations = BusinessLocation::forDropdown($business_id, false);
$customers = Contact::customersDropdown($business_id, false);
$sales_representative = User::forDropdown($business_id, false, false, true);
//Commission agent filter
$is_cmsn_agent_enabled = request()->session()->get('business.sales_cmsn_agnt');
$commission_agents = [];
if (!empty($is_cmsn_agent_enabled)) {
$commission_agents = User::forDropdown($business_id, false, true, true);
}
//Service staff filter
$service_staffs = null;
if ($this->productUtil->isModuleEnabled('service_staff')) {
$service_staffs = $this->productUtil->serviceStaffDropdown($business_id);
}
$shipping_statuses = $this->transactionUtil->shipping_statuses();
return view('sell.index')
->with(compact('business_locations', 'customers', 'is_woocommerce', 'sales_representative', 'is_cmsn_agent_enabled', 'commission_agents', 'service_staffs', 'is_tables_enabled', 'is_service_staff_enabled', 'is_types_service_enabled', 'shipping_statuses'));
}
You can see attached images My aim is how i can use cache::remember on this query.
Controller file
transactions.php file
Extend the transactionUtil file to do the entire query. You also need to gather all parts that are used to construct the query to form a unique key for a unique combination of them. For example this could be a function in the transaction util:
function getFullResult($business_id, $sale_type) {
$queryParameters = array_merge(compact('business_id, sale_type'), request()->all()); // You can filter these into the ones that are used for the query only
$cacheDurationSeconds = 3600;
return Cache::remember('getFullResult'.md5(json_encode($queryParameters)), $cacheDurationSeconds, function () use ($business_id, $sale_type) {
$sells = $this->getListSells($business_id, $sale_type, request()->customer_id);
if (request()->only_subscriptions) {
$sells->where(function ($q) {
$q->whereNotNull('transactions.recur_parent_id')
->orWhere('transactions.is_recurring', 1);
});
}
if (!empty(request()->list_for) && request()->list_for == 'service_staff_report') {
$sells->whereNotNull('transactions.res_waiter_id');
}
// ....
return $sells->where('transactions.is_suspend', 1)
->with($with)
->addSelect('transactions.is_suspend', 'transactions.res_table_id', 'transactions.res_waiter_id', 'transactions.additional_notes')
->get();
});
}
Here I used md5 to generate the unique key since its fast and has an acceptably low likelyhood of hash collisions for this particular use case.
However given the complexity of the query you need to question the likelihood you get multiple of the same parameters in a request because if you won't then caching can't help.

for loop not working correctly with json encode Php

I am trying to fetch members ratings from the database using ajax. I passed a function to the JSON, even though it returned a value in the function but it doesn't execute the for loop condition.
Here is my code, the loop failed to execute. What am I doing wrong?
function mrate($irate) {
$class = "fa-star star-filled";
for ($i = 0; $i < 5; $i++) {
if ($irate <= $i) {
$class = "fa-star-o empty";
}
return '<i class="fa ' . $class . '"></i>';
}
}
$perPage = 2;
if (isset($_GET["page"]) && isset($_GET["page"])) {
$page = $_GET["page"];
$pid = $mysqli->real_string_escape($_GET["pid"]);
} else {
$page = 1;
$pid = $mysqli->real_string_escape($_SESSION['pid']);
};
$startFrom = ($page - 1) * $perPage;
$sqlQuery = "SELECT id, name,
review, rating, added_date
FROM review_rating
where product_id = '$pid'
ORDER BY id ASC LIMIT $startFrom, $perPage";
$result = mysqli_query($mysqli, $sqlQuery);
$paginationHtml = '';
while ($row = mysqli_fetch_assoc($result)) {
$img = '<img class="rounded-circle" width="50" src="' . $set['installUrl'] . 'assets/img/login.png" alt="' . $row["name"] . '"/>';
$irate = $row['rating'];
$paginationHtml .= '<div class="product-review pb-4 mb-4 border-bottom">';
$paginationHtml .= '<div class="d-flex mb-3">';
$paginationHtml .= '<div class="media media-ie-fix align-items-center mr-4 pr-2">' . $img;
$paginationHtml .= '<div class="media-body pl-3"><h6 class="font-size-sm mb-0">' . $row["name"] . '</h6>';
$paginationHtml .= '<span class="font-size-ms text-muted">' . $row['added_date'] . '</span></div></div>';
$paginationHtml .= '<div><div class="star-rating">' . mrate($irate) . '</div></div>';
$paginationHtml .= '</div>';
$paginationHtml .= '<p class="font-size-md mb-2">' . $row['review'] . '</p>';
$paginationHtml .= '</div>';
}
$jsonData = array(
"html" => $paginationHtml,
);
echo json_encode($jsonData);
Replace your function mrate($irate) with this and try. You needed to concatenate the stars code to display it more than once.
function mrate($irate){
$stars = '';
for($i=0; $i<5; $i++){
if($irate <= $i){
$class = "fa-star-o empty";
}else{
$class = "fa-star star-filled";
}
$stars .= '<i class="fa '.$class.'"></i>';
}
return $stars;
}
Assuming there's no fractional rating, you can do the following - Display all 5 stars but solid ones will represent the rating.
function mrate($irate){
$class = '';
for($i = 0; $i < 5; $i++){
if ($irate <= $i) {
$class .= '<i class="fa fa-star"></i>';
} else {
$class .= '<i class="fa fa-star-o"></i>';
}
}
return $class;
}

laravel trying to get property of non object

I'm having an error in laravel 4.2
"Trying to get property of non object"
It was working good before and so I don't know why it's not working now.
This is my code:
Controller:
public function id($lang,$id,$vers) {
// $Agent = new Agent();
// if ($Agent->isMobile()) {
// $data['settings'] = Courses::settings($id, $vers);
// $this->layout->content = View::make('gui.mobile')->with('data', $data);
// } else {
$data['index'] = Courses::productsIndex($id);
$data['langs'] = Courses::langsclient($id);
$data['settings'] = Courses::settings($id, $vers);
$this->layout->content = View::make('gui.home')->with('data', $data);
// }
}
model:
public static function productsIndex($id,$html='') {
$clients = DB::table('clients')->where('client_id',$id)->first();
$clients_settings = DB::table('clients_settings')->where('clients_id',$id)->first();
$courss = explode(',', $clients->products);
$IndexCats = '';
$IndexCats .= '' . trans('home.All Products') .'';
foreach($courss as $index) {
$IndexCats .= '' . trans('home.' . $index) . '';
}
$clients = DB::table('clients')->where('client_id',$id)->first();
$cours = explode(',', $clients->coruses);
$tabs ='';
$links='';
foreach($cours as $row) {
$idcours = DB::table('courses')->where('id',$row)->get();
$coursCount = DB::table('lessons')->where('courses_id',$row)->count();
$clients_settings = DB::table('clients_settings')->where('clients_id',$id)->first();
$clients_images_ebook = DB::table('mediameneger')->where('name','ebook')->where('type','image')->where('client_id',$id)->first();
if($row == 'ebook') {
$image_ebook = !empty($clients_images_ebook->fullpath) ? $clients_images_ebook->fullpath : url() .'/files/images/ebook.jpg';
$tabs .= '<li class="videos ebook" style="background-image: url(' . $image_ebook . '?86400' .');">';
$tabs .= '<p><a href="'. url() .'/gui/' . Request::segment(2) . '/'. $id .'/' . Request::segment(4) . '/ebooks">Ebook';
$tabs .= '<span class="more"><br />';
$tabs .= '<i class="hidden-xs cercale glyphicon glyphicon-book fa-3x"></i></span>';
$tabs .= '</a></p>';
$tabs .= '</li>';
}
if($row == 'ebook_forex') {
$image_ebook = !empty($clients_images_ebook->fullpath) ? $clients_images_ebook->fullpath : url() .'/files/images/ebook.jpg';
$tabs .= '<li class="videos ebook" style="background-image: url(' . $image_ebook . '?86400'.');">';
$tabs .= '<p><a href="'. url() .'/gui/' . Request::segment(2) . '/'. $id .'/' . Request::segment(4) . '/ebooks_forex">Ebook Forex';
$tabs .= '<span class="more"><br />';
$tabs .= '<i class="hidden-xs cercale glyphicon glyphicon-book fa-3x"></i></span>';
$tabs .= '</a></p>';
$tabs .= '</li>';
}
if($row == 'chats') {
$image_ebook = !empty($clients_images_ebook->fullpath) ? $clients_images_ebook->fullpath : url() .'/files/images/chat.jpg';
$tabs .= '<li class="videos chats" style="background-image: url(' . $image_ebook . '?86400'.');">';
$tabs .= '<p><a href="'. url() .'/gui/' . Request::segment(2) . '/'. $id .'/' . Request::segment(4) . '/chats">Chat with an expert';
$tabs .= '<span class="more"><br />';
$tabs .= '<i class="hidden-xs cercale fa fa-weixin fa-3x"></i></span>';
$tabs .= '</a></p>';
$tabs .= '</li>';
}
foreach($idcours as $row2) {
$lang = !empty(Session::get('local')) ? Session::get('local') : 'gb';
$showbox = DB::table('mediameneger')->where('course',$row2->id)->where('lang', $lang)->limit(1)->get();
$clients_images = DB::table('mediameneger')->where('course',$row2->id)->where('type','image')->where('client_id',$id)->first();
foreach ($showbox as $key) {
$lang = Session::get('local') != null ? Session::get('local') : Request::segment(2);
$image = !empty($clients_images->fullpath) ? $clients_images->fullpath : $row2->imagepath;
$tabs .= '<li class="videos" style="background-image: url('. $image . '?86400' .');">';
$tabs .= '<p><a href="'. url() .'/gui/' . $lang . '/' . $id .'/' . Request::segment(4) . '/lessons/' . $row2->id . '">' . trans('home.'. $row2->name . '') . '';
$tabs .= '<span class="more"><i class="text">' . $coursCount . ' ' . trans('home.lessonstotal') .'</i><br />';
$tabs .= '<i class="hidden-xs cercale glyphicon glyphicon-play fa-3x"></i></span>';
$tabs .= '</a></p>';
$tabs .= '</li>';
}
}
}
$tabs .='<li style="overflow: hidden; clear: both; height: 0; position: relative; float: none; display: block;"></li>';
$data['tabs'] = $tabs;
$data['IndexCats'] = $IndexCats;
return $data;
}
The errors is from all the explode();
and I don't know why is working before.
Try to run command "php artisan dump-autoload" and composer "dump-autoload".
Log out of your website and then log back in. This usually happens when you leave the local development server alone for a bit.

Else in foreach looping

What I want if the result is not found from the query select, I want to show else function like:
else {
$html .= 'You have not added stock at all';
}
Because in this case I used string of html, I don't know how to echo the else statement.
More or less my codes is looking like this right now (There are many parts I have removed since it's too long)
<?php
include("../actions/config.php");
$resultsClaim = $mysqli->query("SELECT");
$orders = array();
$html = '';
if ($resultsClaim) {
while($obj = $resultsClaim->fetch_object()) {
$orders[$obj->id_cart][$obj->items] = array('status' => $obj->status ...);
}
foreach ($orders AS $order_id => $order) {
$orderCount = count($order);
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) { $html .= '</tr><tr>'; }
$html .= '<td>' . $item . '</td>';
$row++;
}
$html .= '<div>
<div class="member-popUpeStock'.$data['id'].' member-PopUp">
<div class="member-PopUp-box">
X
<div class="tablePopUp">
<div class="table-row">
<div class="col">: '.$data['method'].' </div>';
///HERE WHERE I WANT TO DO THAT////
else {
echo 'Nothing';
}
echo $html;
?>
Can anyone help me, please! Thanks in Advance.
Since you are taking the no of orders into a variable, you can make use of that directly to see if the orders exists or not.
$orderCount = 0; //Define orderCount in the beginning.
//Rest of the code, till foreach
foreach(){
//Rest of the code here
}
if(intval($orderCount) <= 0) //Using intval, for the case the for loop is not executed at all
{
$html = "Nothing";
}
Here you dont need to concatenate it to $html since you are displaying the table content if order exists or else you displaying "Nothing".
So $html will either have the table content or else "Nothing".
Hope this helps.
First get count of $orders
if (! empty($orders)) {
foreach ($orders AS $order_id => $order) {
// YOUR CODE HERE
}
}
else {
$html .= 'Nothing'; // Append your `no records found` message to the `$html` variable:
}
foreach ($orders AS $order_id => $order) { } else {}
So "}" is missing for foreach loop. Hope it will work for you. Let me know if you need further help.
Give it a try
<?php
include("../actions/config.php");
$resultsClaim = $mysqli->query("SELECT");
$orders = array();
$html = '';
if (!empty($resultsClaim)) {
while ($obj = $resultsClaim->fetch_object()) {
$orders [$obj->id_cart][$obj->items] = array('status' => $obj->status);
}
foreach ($orders AS $order_id => $order) {
$orderCount = count($order);
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) {
$html .= '</tr><tr>';
}
$html .= '<td>' . $item . '</td>';
$row++;
}
$html .= '<div>
<div class="member-popUpeStock' . $data['id'] . ' member-PopUp">
<div class="member-PopUp-box">
X
<div class="tablePopUp">
<div class="table-row">
<div class="col">: ' . $data['method'] . ' </div>';
}
}
///HERE WHERE I WANT TO DO THAT////
else {
echo 'Nothing';
}
echo $html;
?>

migrating two pieces of code, error mysql_fetch_array() expects parameter 1 to be resource

I have migrated some codes, all went fine till I encountered this code in the tutorial. Because I have a custome template, the html and php code is a little different from the original template, now I'm totally lost.
This is the original code, which should be replaced with the one beneath this code:
<table cellspacing="0" cellpadding="0" border="0" class="product">
<tr>
<td width="103" height="104"><script language="javascript"><!--
document.write('<?php echo '
<a href="javascript:popupWindow(\\\'' .
tep_href_link(FILENAME_POPUP_IMAGE, 'pID=' .
$product_info['products_id']) . '\\\')">'
. tep_image(DIR_WS_IMAGES .
$product_info['products_image'], addslashes(
$product_info['products_name']),
SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT, 'hspace="0" vspace="0"') . '</a>'; ?>');
//--></script>
<noscript>
<?php echo '<a href="' . tep_href_link(DIR_WS_IMAGES .
$product_info['products_image']) . '" target="_blank">' .
tep_image(DIR_WS_IMAGES .
$product_info['products_image'],
$product_info['products_name'],
SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT, 'hspace="0" vspace="0"') . '</a>'; ?>
</noscript></td>
<td width="344" height="104"><br>
<br style="line-height:5px"><?php echo stripslashes(
$product_info['products_description']); ?>
<br style="line-height:1px;"><br style="line-height:5px;">
</td>
</tr>
<tr>
<td width="447" height="1" colspan="2">
<img src="images/3_line.gif" alt="" border="0"><br></td>
</tr>
<tr>
<td height="38">
<br style="line-height:12px"><script language="javascript"><!--
document.write('<?php echo '
<div style=" text-align:center; width:90%;">
<a href="javascript:popupWindow(\\\''
. tep_href_link(FILENAME_POPUP_IMAGE, 'pID=' .
$product_info['products_id']) . '\\\')">'
. TEXT_CLICK_TO_ENLARGE . '</a></div><br style="line-height:2px;">'; ?>');
//--></script>
<noscript>
<?php echo '<div style=" text-align:center; width:90%;">
<a href="' . tep_href_link(DIR_WS_IMAGES .
$product_info['products_image']) . '" target="_blank">
<br style="line-height:7px">' . TEXT_CLICK_TO_ENLARGE . '</a>
</div>
<br style="line-height:2px;">'; ?>
</noscript>
</td>
<td style=" vertical-align:middle; padding-left:20px;"><strong>
<?=$products_price?></strong><br></td>
</tr>
</table>
This is the code I had to replace with the original one (the one above this code):
<!-- Simple multi image addon -->
<div id="fancy">
<table border="0" cellspacing="0" cellpadding="2" align="right">
<tr>
<td align="center" class="smallText">
<?php
if (strlen($product_info['products_name']) >
$max_title_length)
{
$title = wordwrap(htmlspecialchars($product_info['products_name']),
$max_title_length, '<br>');
}
else
{
$title = htmlspecialchars($product_info['products_name']);
}
$m_source = '';
$thumb = (class_exists('oscthumb') && CFG_MASTER_SWITCH == 'On');
if ($thumb)
{
preg_match('/"([^"]+)"/', htmlentities(tep_image(
DIR_WS_IMAGES .
$product_info['products_image'], '', '', '', '', '', 5),
ENT_NOQUOTES), $image);
$m_source = str_replace('&', '&', $image[1]);
}
echo '<a rel="image_group" title="' . $title . '" href="' . (
$m_source ? $m_source : DIR_WS_IMAGES .
$product_info['products_image']) . '"
alt="' . $product_info['products_name'] . '" target="_blank">' .
tep_image(DIR_WS_IMAGES . $product_info['products_image'],
$product_info['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT,
'hspace="5" vspace="5"', false, 5) . '
<br /></a>';
if (!$vertical_format)
{
echo '';
$row = 1;
reset($products_image_array);
foreach ($products_image_array as $value)
{
if ($thumb)
{
$source = '';
preg_match('/"([^"]+)"/', htmlentities(
tep_image(DIR_WS_IMAGES . $value, '', '', '', '', '', 5), ENT_NOQUOTES),
$image);
$source = str_replace('&', '&', $image[1]);
}
echo '<a rel="image_group" title="' . $title . '" href="' . (
$source ? $source : DIR_WS_IMAGES . $value) . '" target="_blank">' .
tep_image(DIR_WS_IMAGES . $value, $product_info['products_name'],
TINY_IMAGE_WIDTH, TINY_IMAGE_HEIGHT, 'hspace="5" vspace="5"') .
'</a>';
++$row;
if ($row > $image_group)
{
echo '<br />';
$row = 1;
}
}
}
echo '</td>';
if ($vertical_format)
{
echo '<td>';
$row = 1;
reset($products_image_array);
foreach ($products_image_array as $value)
{
if ($thumb)
{
$source = '';
preg_match('/"([^"]+)"/', htmlentities(
tep_image(DIR_WS_IMAGES . $value, '', '', '', '', '', 5),
ENT_NOQUOTES), $image);
$source = str_replace('&', '&', $image[1]);
}
echo '<a rel="image_group" title="' .
$title . '" href="' . ($source ? $source : DIR_WS_IMAGES . $value) . '"
target="_blank">' .
tep_image(DIR_WS_IMAGES . $value, $product_info['products_name'],
TINY_IMAGE_WIDTH, TINY_IMAGE_HEIGHT, 'hspace="5" vspace="5"') .
'<br />' . '</a>';
++$row;
if ($row > $image_group)
{
echo '</td><td>';
$row = 1;
}
}
echo '</td>';
}
?>
</tr>
<?php
echo
'<tr><td class="smallText">' . TEXT_CLICK_TO_ENLARGE . '</td></tr>';
?>
</table>
</div>
<!-- EOF Simple multi image addon -->
This is the error it produces on my website:
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in..
includes/functions/database.php on line 99
This is line 99
function tep_db_fetch_array($db_query) {
return mysql_fetch_array($db_query, MYSQL_ASSOC);
}
Any help would be great, excuse me for the formatting of the code, i tried to make it as good as possible, but some echo lines are to long.
Edit:
Posting here, complete database.php
<?php
/*
$Id: database.php,v 1.21 2003/06/09 21:21:59 hpdl Exp $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
function tep_db_connect(
$server = DB_SERVER,
$username = DB_SERVER_USERNAME,
$password = DB_SERVER_PASSWORD,
$database = DB_DATABASE,
$link = 'db_link') {
global $$link;
if (USE_PCONNECT == 'true') {
$$link = mysql_pconnect($server, $username, $password);
} else {
$$link = mysql_connect($server, $username, $password);
}
if ($$link) mysql_select_db($database);
return $$link;
}
function tep_db_close($link = 'db_link') {
global $$link;
return mysql_close($$link);
}
function tep_db_error(
$query, $errno, $error) {
die('<font color="#000000">
<b>' . $errno . ' - ' . $error . '<br><br>' .
$query . '<br><br><small><font color="#ff0000">
[TEP STOP]</font></small><br><br></b></font>');
}
function tep_db_query($query, $link = 'db_link') {
global $$link;
if (defined('STORE_DB_TRANSACTIONS') && (
STORE_DB_TRANSACTIONS == 'true')) {
error_log('QUERY ' .
$query . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
}
$result = mysql_query($query, $$link) or
tep_db_error($query, mysql_errno(), mysql_error());
if (defined('STORE_DB_TRANSACTIONS') && (
STORE_DB_TRANSACTIONS == 'true')) {
$result_error = mysql_error();
error_log('RESULT ' . $result . ' ' .
$result_error . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
}
return $result;
}
function tep_db_perform($table, $data, $action = 'insert',
$parameters = '', $link = 'db_link') {
reset($data);
if ($action == 'insert') {
$query = 'insert into ' . $table . ' (';
while (list($columns, ) = each($data)) {
$query .= $columns . ', ';
}
$query = substr($query, 0, -2) . ') values (';
reset($data);
while (list(, $value) = each($data)) {
switch ((string)$value) {
case 'now()':
$query .= 'now(), ';
break;
case 'null':
$query .= 'null, ';
break;
default:
$query .= '\'' . tep_db_input($value) . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ')';
} elseif ($action == 'update') {
$query = 'update ' . $table . ' set ';
while (list($columns, $value) = each($data)) {
switch ((string)$value) {
case 'now()':
$query .= $columns . ' = now(), ';
break;
case 'null':
$query .= $columns .= ' = null, ';
break;
default:
$query .= $columns . ' = \'' . tep_db_input($value) . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ' where ' . $parameters;
}
return tep_db_query($query, $link);
}
function tep_db_fetch_array($db_query) {
line 99
return mysql_fetch_array($db_query, MYSQL_ASSOC);
}
function tep_db_num_rows($db_query) {
return mysql_num_rows($db_query);
}
function tep_db_data_seek($db_query, $row_number) {
return mysql_data_seek($db_query, $row_number);
}
function tep_db_insert_id() {
return mysql_insert_id();
}
function tep_db_free_result($db_query) {
return mysql_free_result($db_query);
}
function tep_db_fetch_fields($db_query) {
return mysql_fetch_field($db_query);
}
function tep_db_output($string) {
return htmlspecialchars($string);
}
function tep_db_input($string, $link = 'db_link') {
global $$link;
if (function_exists('mysql_real_escape_string')) {
return mysql_real_escape_string($string, $$link);
} elseif (function_exists('mysql_escape_string')) {
return mysql_escape_string($string);
}
return addslashes($string);
}
function tep_db_prepare_input($string) {
if (is_string($string)) {
return trim(tep_sanitize_string(stripslashes($string)));
} elseif (is_array($string)) {
reset($string);
while (list($key, $value) = each($string)) {
$string[$key] = tep_db_prepare_input($value);
}
return $string;
} else {
return $string;
}
}
?>
The first tep_fetch_array
// Simple multi image addon
$image_group = TINY_IMAGE_GROUP_SIZE; //Number of images to show per row/column
$vertical_format = (ADDITIONAL_IMAGE_FORMAT == 'vertical');
$max_title_length = 40; //Set the maximm length of popup titles before they are broken into multiple lines.
$product_info_query = tep_db_query("select p.products_id, pd.products_name,
pd.products_description, p.products_model, p.products_quantity, p.products_image,
p.products_image_array, pd.products_url, p.products_price,
p.products_tax_class_id, p.products_date_added,
p.products_date_available, p.manufacturers_id from "
. TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where
p.products_status = '1' and p.products_id = '" . (int)
$HTTP_GET_VARS['products_id'] . "' and
pd.products_id = p.products_id and
pd.language_id = '" . (int)$languages_id . "'");
$product_info = tep_db_fetch_array(
$product_info_query);
$products_image_array = unserialize($product_inf0
['products_image_array']);
if (!is_array($products_image_array)) $products_image_array = array();
// EOF Simple multi image addon
Given that error message, the $db_query you're passing in to the tep_db_fetch_array() is obviously not set properly. Somewhere it's getting nulled out, overwritten, referred to out of scope, or you've got a typo in a parameter somewhere.

Categories