Get all order in shoplify API - php

I am trying it fetch all orders from the specific date range in Shopify. The problem is I am only able to get 250 orders. I am using the following code.
<div id="main-content1">
<div class="container-fluid">
<?php
function nextorders($lastorderno,$orderfm,$orderto,$orders) {
$orders_obj_url = 'XXXXXXXXXXXXXXXXXXX.myshopify.com/admin/api/2019-10/orders.json&since_id='.$lastorderno.'&status=any&created_at_min='.$orderfm.'T00:00:00&created_at_max='.$orderto.'T23:59:59&fields=created_at,id,order_status_url,total_price_set,number,note,note_attributes';
$orders_content = #file_get_contents( $orders_obj_url );
$orders_json = json_decode( $orders_content, true );
$orders_new = $orders_json['orders'];
$orders = $orders_json['orders'];
if ($remaningprder > 0) {
$lastorderno = $orders['0']["number"];
nextorders($lastorderno,$orderfm,$orderto,$orders_new);
}
return $orders_new;
}
if ($_POST) {
$orderfm = date("Y-m-d", strtotime($_POST['start']));
$orderto = date("Y-m-d", strtotime($_POST['end']));
$orders_obj_url = 'XXXXXXXXXXXXXXXXXXX.myshopify.com/admin/api/2019-10/orders.json?limit=250&fields=created_at,id,order_status_url,total_price_set,number,note,note_attributes&status=any&created_at_min='.$orderfm.'T00:00:00&created_at_max='.$orderto.'T23:59:59';
$orders_content = #file_get_contents( $orders_obj_url );
$orders_json = json_decode( $orders_content, true );
$orders = $orders_json['orders'];
if (count($orders) > 249) {
$remaningprder = $total_order - count($orders);
$lastorderno = $orders['0']["number"];
$orders = nextorders($lastorderno,$orderfm,$orderto,$orders);
}
}
?>
<div class="row clearfix" style="margin-top:20px;margin-bottom:20px;">
<div class="offset-lg-3 offset-md-3 col-lg-6 col-md-6">
</div>
<div class="offset-lg-3 offset-md-3 col-lg-6 col-md-6">
<div>
<form method="POST" action="">
<label>Date Range</label>
<div class="input-daterange input-group" data-provide="datepicker">
<input type="text" class="input-sm form-control" value="<?=$startset;?>" name="start" autocomplete="off">
<span class="input-group-addon range-to">to</span>
<input type="text" class="input-sm form-control" value="<?=$endset; ?>" name="end" autocomplete="off">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12">
<div class="card">
<div class="header">
<h2>Last order</h2>
<ul class="header-dropdown dropdown">
<li><i class="icon-frame"></i></li>
</ul>
</div>
<div class="body">
<div class="table-responsive hide-table">
<?php if (count($orders) > 0) { ?>
<table class="table table-striped table-hover dataTable js-exportable">
<thead>
<tr>
<th>#</th>
<th>Order No</th>
<th>Amount</th>
<th>Token</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
foreach ($orders as $order) {
?>
<tr>
<th scope="row" data-title="Date"><?=$i++;?></th>
<td data-title="Order No"><?=$order["number"];?></td>
<td data-title="Amount"><?=$order["total_price_set"]["shop_money"]["amount"];?></td>
<td data-title="Token"></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And then use the $orders variable to create the output table. It is only sowing 250 orders even if I increase the order limit.
Can anyone help me with this
Thanks

This is an old question I know, but perhaps someone can find use of this answer.
There is a way to get all orders by using the since_id option in the fetch url and cURL. This way you get 250 (or a number of your choosing below 250 since that is the max number you can fetch in one go) orders, starting with the order id 0. This will start at the first order. From here, you loop and fetch orders from (using since_id) the last order in the previous call. And when the number of orders returned is below the number of orders you fetch in each call, you exit.
Example from a Symfony (5) app:
private function getShopifyOrders(): array
{
$this->store_name = $this->params->get('app.shopify_store_name');
$this->api_key = $this->params->get('app.shopify_api_key');
$this->api_pass = $this->params->get('app.shopify_password');
$this->api_url = 'https://' . $this->api_key . ':' . $this->api_pass . '#' . $this->store_name;
$last = 0;
$allOrders = [];
while (true) {
$orders_url = $this->api_url . '/admin/orders.json?limit=250&status=any&since_id=' . $last;
error_log($orders_url); // Show each call in the log for reference
$ch = curl_init($orders_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$orders = json_decode($response);
foreach ( $orders->orders as $order ) {
$allOrders[] = $order;
$last = $order->id;
}
if ( count( $orders->orders ) < 250 ) {
break;
}
}
return $allOrders;
}

You need to use the page_info-based paging that Shopify uses. Essentially, you need to look at the headers of the return, and call a new URL from there if applicable (if there are more results available).
Unfortunately this means you can't use get_file_contents() since it doesn't allow you to view the headers. Check out curl or another library to make proper HTTP requests.
The relevant Shopify docs are here: https://help.shopify.com/en/api/guides/paginated-rest-results

Related

How to display data from multiple table with php

Here is my Song.php code which i created a class so i can use it in the index.php file
<?php
require_once("dbInfo.php");
Class Song{
public $length;
public $picture;
public $urlSong;
public $songId;
public $lastname;
public static function getAllRecords($pageNo, $pageSize, &$totalRecords) {
// Connect to database.
$options = array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=" . DatabaseInfo::getServer() . ";dbname=" . DatabaseInfo::getDatabaseName() . ";charset=utf8";
$conn = new PDO($dsn, DatabaseInfo::getUserName(), DatabaseInfo::getPassword(), $options);
$pageNo = (int)$pageNo;
$pageSize = (int)$pageSize;
$sql = "SELECT COUNT(*) AS Count
FROM `
(SELECT song.SongId,song.Picture,song.Length,song.UrlSong,artist.Lastname FROM song LEFT JOIN
songandartist on song.SongId= songandartist.SongId INNER JOIN artist on songandartist.ArtistId=artist.ArtistId)AS T1`";
// Prepare statement.
$stmt = $conn->prepare($sql);
// Execute the statement.
$stmt->execute();
// Get total records count.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$totalRecords = $row['Count'];
$stmt = NULL;
$totalPages = ceil($totalRecords / $pageSize);
if ($pageNo > $totalPages) {
$pageNo = $totalPages;
}
$start = $pageSize * $pageNo - $pageSize;
if($start < 0) {
$start = 0;
}
$sql = "SELECT `Length`,`Picture`,`SongId`,`Lastname`,`UrlSong` FROM
`(SELECT song.SongId,song.Picture,song.Length,song.UrlSong,artist.Lastname FROM song left join songandartist on song.SongId= songandartist.SongId INNER JOIN artist on songandartist.ArtistId=artist.ArtistId)AS T1`
LIMIT $start, $pageSize;";
// Prepare statement.
$stmt = $conn->prepare($sql);
// Execute the statement.
$stmt->execute();
// Fetch all records.
$list = Array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$song = new GetAllSong();
$song->length = $row["Length"];
$song->picture = $row["Picture"];
$song->songId = $row["SongId"];
$song->lastname = $row["Lastname"];
$song->urlSong = $row["UrlSong"];
array_push($list, $song);
}
// Close the database connection.
$conn = NULL;
return $list;
}
}
?>
And here is my index.php code, i called the class and used the function but it did not work
<?php
include '../Song.php';
?>
<div class="container">
<div class="row py-5">
<div class="col-lg-12 mx-auto">
<div class="p-5 rounded shadow "
style="border-radius: 1rem;background-color: rgba(255, 255, 255, 0.58);">
<h2 class="mb-5">Table Song</h2>
<div class="p-1 bg-light rounded rounded-3 shadow-sm mb-4">
<div class="input-group">
<input type="search" placeholder="Search..." aria-describedby="button-addon1" class="form-control border-0 bg-light">
<div class="input-group-append">
<button id="button-addon1" type="submit" class="btn btn-link text-primary"><strong><i class="bi bi-search"></i></strong></button>
</div>
</div>
</div>
<form class="col-lg-8"name="get_Song" action="<?php echo $_SERVER['PHP_SELF'] ?>?page=listsong" method="POST" enctype="multipart/form-data">
<div class="form-row mb-4 align-items-center">
<!-- <label class="fs-5 fw-bold text-secondary mr-0" for="inlineFormInput">Page No</label>-->
<div class="col-sm-4">
<input type="number" class="form-control form-control-lg mb-2 border-0" name="PageNo" id="PageNoid" placeholder="Page No">
</div>
<!-- <label class="fs-5 fw-bold text-secondary mr-0" for="inlineFormInputGroup">Page Size</label> -->
<div class="col-sm-4">
<input type="number" class="form-control form-control-lg mb-2 border-0" name="PageSize" id="Pagesizeid" placeholder="Page Size">
</div>
<div class="col-sm-3 text-center">
<input type="submit" class="btn btn-info mb-2 form-control-lg fs-5 fw-bold" id="ResetId" name="reset" value="Reset" />
</div>
</div>
</form>
<div class="table-responsive custom-table-responsive">
<table class="table custom-table">
<thead>
<tr>
<th scope="col">
<label class="control control--checkbox">
<input type="checkbox" class="js-check-all" />
<div class="control__indicator"></div>
</label>
</th class="">
<th scope="col">SongId</th>
<th scope="col">Lastname</th>
<th scope="col">Length</th>
<th scope="col">Picture</th>
<th scope="col">UrlSong</th>
</tr>
</thead>
<tbody>
<?php
$pageNo = 1;
$pageS = 4;
if (!empty($_POST['reset'])) {
$pageNo = $_POST['PageNo'];
$pageS = $_POST['PageSize'];
}
$getdb = new Song();
$arr = $getdb->getAllRecords($pageNo, $pageS, $totalRecords);
// $strTbl = "";
//
// $stt = 1;
for ($i = 0; $i < count($arr); $i++) {
$obj = $arr[$i];
?>
<tr scope='row'>
<th scope="row">
<label class="control control--checkbox">
<input type="checkbox" />
<div class="control__indicator"></div>
</label>
</th>
<td> <?php echo $obj->songId ?></td>
<td> <?php echo $obj->lastname ?></td>
<td> <?php echo $obj->length ?></td>
<td> <?php echo $obj->picture ?></td>
<td> <?php echo $obj->urlSong ?></td>
<td>
<div style='display:flex;'>
<a href="Admin.php?page=addsong&id=<?php echo $obj->songId; ?>" class='btn btn-info mr-1' id='updatef'><i class='i bi-arrow-repeat'></i></a>
<a href="../backend/delete/delsong.php?id=<?php echo $obj->songId; ?>" class='btn btn-danger mr-1' id='deletef'><i class='bi bi-trash'></i></a>
</div>
</td>
</tr>
<tr class="spacer"><td colspan="100"></td> </tr>
<?php } ?>
</tbody>
</table>
<?php
if (!empty($_POST['reset'])) {
echo "Page : " . $pageNo . " " . "Size: " . $pageS;
}
;
?>
</div>
</div>
</div>
</div>
</div>
I want to display multiple tables from the database with these code, but it did not work, it only showed the blank page without any errors when i click the button. I tried to change the sql to echo test and it worked, so i think the problem in my code is that i did not use the right sql statement.Please help me with this, thank you very much.
I can see a couple of problems.
First, in index.php you're calling an instance method, rather than a static method. Instead of
$getdb = new Song();
$arr = $getdb->getAllRecords($pageNo, $pageS, $totalRecords);
You should use
$arr = Song::getAllRecords($pageNo, $pageS, $totalRecords);
... but that's not what's causing your error.
In your class definition, you have
$song = new GetAllSong();
but I think it should be
$song = new Song();
Also although I can't see an error with your SQL, I'm not sure why you're using a nested query. It might be easier and more peformant to use a simple SQL statement?
Edit: Also you have an SQL injection vulnerability. You're taking whatever someone has POSTed and passing it directly into your SQL statement. If someone crafts a malicious POST request to your web page they could perform whatever SQL they wanted to on your database.

PHP Output (PDO & CRUD)

I need help with my PHP script.
I have 3 Tables in my Database (its German so sorry if you dont understand ^^):
-firma (in english company)
-produkt (in english product)
-firmaprodukt (in english companyproduct)
If I click on a company, the product image should be output (from the "Produkt" database) and the appropriate URL (from the "firmaprodukt").
So far I've managed that when you click on a company, the ID is displayed (example: "localhost/TESTING//index?1=") but I'm struggling with the output.
That's my index.php script for the output:
<div class="col-xl-6">
<div id="login_content">
<div class="scrollP">
<?php
$fpresults = $fpCrud->getPicUrl($FirmenID);
?>
<div class="col-12 d-flex justify-content-center heading-div">
<h3> <?= $result['firmenname']?> </h3>
</div>
<table border="0">
<tbody>
<?php
foreach ($fpresults as $fpresult){
?>
<tr>
<div class="box customer-box" data-parent="#login_card" id="project_reg_box">
<img src="dashboard/TESTING/<?= $fpresult['ProduktLogo']?>" height="100%" >
</div>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
And that's in my crud.php:
public function getPicUrl($FirmenID) {
$stmt = $this->conn->query(
"SELECT fp.FirmenID, f.firmenname, p.ProduktLogo, fp.url
FROM firma f
JOIN firmaprodukt fp ON fp.FirmenID = f.FirmenID
JOIN produkt p ON fp.ProduktID = p.ProduktID
WHERE fp.FirmenID = :FirmenID");
$stmt->execute(array(':FirmenID' => $FirmenID));
$data = $stmt->fetch();
return $data;
}
In my formprocess.php I don't have anything for that.
My solution:
index.php
<?php
if (isset($_GET['firmaprodukte'])) {
$FirmenID = (int) $_GET['firmaprodukte'];
$firmaprodukte = $fpCrud->getPicUrl($_GET['firmaprodukte']);
$firmenresults = $firmaCrud->getFirma($_GET['firmaprodukte']);
?>
<div class="col-xl-6">
<div class="scrollP">
<div id="login_content">
<div id="login_card" class="container">
<?php
$fpresults = $fpCrud->getPicUrl($FirmenID);
?>
<div class="col-12 d-flex justify-content-center heading-div">
<h3> <?= $firmenresults['firmenname']?> </h3>
</div>
<table border="0">
<tbody>
<?php
foreach ($fpresults as $fpresult){
?>
<tr>
<div class="box customer-box" data-parent="#login_card" id="project_reg_box">
<img src="dashboard/TESTING/<?= $fpresult['ProduktLogo']?>" height="80vh" max-width="200vh">
</div>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php } ?>
Crud.php
public function getPicUrl($FirmenID) {
$stmt = $this->conn->prepare("SELECT fp.FirmenID, f.firmenname, p.ProduktLogo, fp.url FROM firma f JOIN firmaprodukt fp ON fp.FirmenID = f.FirmenID JOIN produkt p ON fp.ProduktID = p.ProduktID WHERE fp.FirmenID = :FirmenID");
$stmt->execute(array(':FirmenID' => $FirmenID));
$data = $stmt->fetchAll();
return $data;
}
formprocess.php
if(isset($_POST['firmaprodukte'])) {
$FirmenID = $_POST['FirmenID'];
if($crud->getPicUrl($FirmenID)) {
header('location: FirmaProdukt.php');
exit;
} else{
header('location: FirmaProdukt.php');
exit;
}
}

How to find the difference between event dates in the time line using php?

Actually I am working on the 2002 ( old php project) based on the requirement. So my work is to show the difference between events markers based on the dates by placing some width dynamically in php. So I wrote the code after that it is not even displaying the events markers in the page.
I will provide the code which I wrote for this requirement.
function getEvents($uid)
{
$timeLineQry = mysql_query("select * from timelines where user_id = $uid and status=1 order by id desc");
if(mysql_num_rows($timeLineQry) > 0)
{
$data='';
while($tres = mysql_fetch_assoc($timeLineQry))
{
$data.='<div class="events-chat" id="timeline'.$tres['id'].'">
<button class="btn btn-success" onclick="addEvent('.$tres['id'].')"> Add Event</button>
<div id="" style="float:right;">
<span style="margin-left: 10px;color: #696767;
cursor: pointer;margin-right: 25px;font-size: 16px;font-weight: bolder;font-family: inherit;" onclick="getTimeLine(\''.$tres['title'].'\',\''.$tres['description'].'\',\''.$tres['id'].'\')">'.$tres['title'].'</span>
<i class="glyphicon glyphicon-trash" onclick="deleteTimeline('.$tres['id'].')"></i>
</div>
<div style="clear:both;margin-bottom:35px;"></div>
<div id="eventBlck'.$tres['id'].'">';
//echo "select * from events where user_id = $uid and timeline=".$tres['id'];exit;
$user_exe1 = mysql_query("select * from events where user_id = $uid and timeline=".$tres['id']." order by date asc");
if(mysql_num_rows($user_exe1) > 0) {
$i=1;
$data.='<div class="events-chat-inner">
<div class="all-cht-blk">
<div class="event-border">
<div class="c-dot" style="float:left;position:absolute;left:-4px;top:-4px;"></div>
<div class="c-dot" style="float:right;position:absolute;right:-4px;top:-4px;"></div>
</div>
';
while($res = mysql_fetch_assoc($user_exe1))
{
//Here is the code I just tried to subtract the date of one event from date of another event.
$datecount = count($res['date']);
for($j = 0; $j <= $datecount; $j++){
$previous_event_date = strtotime($res['date'][j]);
$present_event_date = strtotime($res['date'][j+1]);
$distance = $previous_event_date - $present_event_date;
$distance = floor($distance/(60 * 60 * 24));
$case1 = range(0,20);
$case2 = range(1,40);
if(in_array($distance,$case1))
{
$distancestyle = 'width:130px';
}
elseif(in_array($distance,$case2))
{
$distancestyle = 'width:180px';
}
else
{
$distancestyle = 'width:230px';
}
if($i%2==0){$bc='#f45e34';}else if($i%3==0){$bc='#fa454a';}else if($i%4==0){$bc='#3cb54b';}else if($i%5==0){$bc='#03aeac';}else{$bc='#9f388b';}
if($i%2==0)
{
$data.='<div class="event-ct-blk" style='\$distancestyle\'>
<h3 onclick="getData('.$res['id'].',
\''.str_replace("'","\'",$res['name']).'\',
\''.str_replace("'","\'",$res['description']).'\',
\''.date('m-d-Y',strtotime($res['date'])).'\');">'.$res['name'].'</h3>
<p onclick="getData('.$res['id'].',\''.str_replace("'","\'",$res['name']).'\',\''.str_replace("'","\'",$res['description']).'\',\''.date('m-d-Y',strtotime($res['date'])).'\');">'.$res['description'].' </p>
<div class="pointer">
<div class="c-dot"></div>
<div class="p-strip-2" style="height:125px;"></div>
<div class="q-circle-outer" onclick="getData('.$res['id'].',\''.str_replace("'","\'",$res['name']).'\',\''.str_replace("'","\'",$res['description']).'\',\''.date('m-d-Y',strtotime($res['date'])).'\');">
<div class="q-circle" style="background: '.$bc.';"></div>
</div>
<div class="p-strip" style="height:25px;"></div>
<div class="c-dot"></div>
</div>
<p class="q-date" onclick="getData('.$res['id'].',
\''.str_replace("'","\'",$res['name']).'\',
\''.str_replace("'","\'",$res['description']).'\',
\''.date('m-d-Y',strtotime($res['date'])).'\');"> Date: '.date('M-d-Y',strtotime($res['date'])).' </p>
</div>';
}
else
{
$data.='<div class="event-ct-blk" style='\$distancestyle\'>
<h3 onclick="getData('.$res['id'].',\''.str_replace("'","\'",$res['name']).'\',\''.str_replace("'","\'",$res['description']).'\',\''.date('m-d-Y',strtotime($res['date'])).'\');">'.$res['name'].'</h3>
<p onclick="getData('.$res['id'].',\''.str_replace("'","\'",$res['name']).'\',\''.str_replace("'","\'",$res['description']).'\',\''.date('m-d-Y',strtotime($res['date'])).'\');">'.$res['description'].' </p>
<div class="pointer">
<div class="c-dot"></div>
<div class="p-strip" style="height:25px;"></div>
<div class="q-circle-outer" onclick="getData('.$res['id'].',\''.str_replace("'","\'",$res['name']).'\',\''.str_replace("'","\'",$res['description']).'\',\''.date('m-d-Y',strtotime($res['date'])).'\');">
<div class="q-circle" style="background: '.$bc.';"></div>
</div>
<div class="p-strip-2" style="height:125px;"></div>
<div class="c-dot"></div>
</div>
<p class="q-date" onclick="getData('.$res['id'].',\''.str_replace("'","\'",$res['name']).'\',\''.str_replace("'","\'",$res['description']).'\',\''.date('m-d-Y',strtotime($res['date'])).'\');"> Date: '.date('M-d-Y',strtotime($res['date'])).' </p>
</div>';
}
$i++;
}
$data.='</div></div>';
}
else
{
$data.='<div class="event-border" style="width:96%;">
<div class="c-dot" style="float:left;position:absolute;left:-4px;top:-4px;"></div>
<div class="c-dot" style="float:right;position:absolute;right:-4px;top:-4px;"></div>
</div><div style="text-align:center;margin-top:78px;font-size: 18px;"><p>No events added.</p></div>';
}
$data.='</div></div>';
}
}
else
{
$data='<div class="events-chat" id="timeline1"> <button class="btn btn-success" onclick="addEvent(1)"> Add Event</button><div style="clear:both;margin-bottom:35px;"></div><div id="eventBlck1"> <div class="event-border" style="width:96%;">
<div class="c-dot" style="float:left;position:absolute;left:-4px;top:-4px;"></div>
<div class="c-dot" style="float:right;position:absolute;right:-4px;top:-4px;"></div>
</div><div style="text-align:center;margin-top:78px;font-size: 18px;"><p>No events added.</p></div></div></div>';
}
}//end for loop
return $data;
}
In this code I place the code which I marked as the comments and actually this is the code I have present but after working on this file events are not showing canyou please see the issue in this code or any errors.

Update shopping cart - error when changing quantity of products.. Cakephp 3.8

Friends, I am trying to update my shopping cart based on this article.
However, I cannot update the "quantity" value separately in the session. The article works with the products registered in the database. I use session. I believe that there is some detail in cart.ctp that is not correct in this transition! I appreciate if anyone can see what's going on!
cart.ctp
The code for my cart.ctp is as follows:
<html>
<body>
<main class="mt-1 pt-1">
<div class="container wow fadeIn">
<div class="row">
<div class="col-md-8 mb-4">
<div class="card">
<?php foreach($this->Session->read('carrinho') as $index=>$carrinho): ?>
<div class="container">
<div class="row">
<div class="col-md-10">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">product</th>
<th scope="col">price</th>
<th scope="col">Qte</th>
<th scope="col">subtotal</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">
<?= $carrinho->has('produto') ? $this->Html->link($carrinho->produto->nome_produto, ['controller' => 'Produtos', 'action' => '/', $carrinho->produto->id]) : '' ?>
</th>
<td>
<strong>R$ <?php echo number_format($carrinho->produto->preco, 2, ',', '') ?></strong>
</td>
<td>
<?php echo $this->Form->create('Pedidos',array('id'=>'add-form',
'url'=>array('controller'=>'pedidos','action'=>'update',$carrinho->produto->id)));?>
<?php
echo $this->Form->control('quantidade',
array('type'=>'number', 'label'=>false,'min'=> 1,'size' => 2,
'maxlenght' => 2, 'class'=>'form-control','required' => 'true', 'value'=>$carrinho->quantidade));?> un.
<?php echo $this->Form->submit('update',array('class'=>'btn-md text-white waves-effect m-1', 'style' => 'background-color:#1ab394'));?>
<?php echo $this->Form->end();?>
</td>
<td>
<strong>
R$ <?php
$sub = ($carrinho->produto->preco * $carrinho->quantidade);
echo number_format($sub, 2, ',', '');
?>
</strong>
<?php $total = array(number_format($sub, 2, ',', ''));?>
</td>
</tr>
</tbody>
</table>
<hr width="40%">
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
</div>
<div class="col-md-2 mt-3">
<?= $this->Html->link(__('Update'), ['action' => 'update']); ?>
</div>
<div class="col-md-2 mt-3">
<?= $this->Html->link(__('Delete'), ['action' => 'delete', $index]); ?>
</div>
</div>
<?php endforeach; ?>
<br>
</div>
</div>
<div class="col-md-4 mb-4">
<form class="card p-2">
<div class="input-group">
<?= $this->Html->link(__('Checkout'), ['action' => 'checkout']); ?>
</div>
<?php echo $this->Form->end(); ?>
</div>
</div>
</div>
</main>
</body>
</html>
cart.php
public function update($productId = null) {
$session = $this->request->session();
$carrinho = $session->read('carrinho');
$quantidade = $this->request->data('quantidade');
if ($quantidade > 0) {
$carrinho[$productId] = $quantidade;
$session->write('carrinho', $carrinho);
return $this->redirect(['action' => 'index']);
}
}
Your edit resolves one major issue, which is that you were starting multiple forms inside td elements, but not ending them until much later. That would produce invalid HTML. Note that you still have your original $this->Form->end() call after the end of the table, that should be removed.
The main problem that you've got here is that your forms have zero information about what row they are supposed to be updating. You need to include some reference to which cart item, presumably either including $cart->product->id in the URL, like you have included $index in your delete function, or else as a hidden input in the form.
The second problem here is that you seem to think that the posted data is going to have some structure that it's not. You've named your control simply "quantity". That's all that's going to be in the data. You will have $this->request->data['quantity'], and it's just a single integer value, not an array you can foreach over. Hence that particular error.
And third, you are then trying to access $this->request->data['Carrinho']['produto_id'], which very much doesn't exist. Seems like you're trying to get the product ID from here, but (per the first issue above) you've never added that into the form.
So, something like this should resolve it all:
<?php echo $this->Form->create('Requests',array('id'=>'add-form',
'url'=>array('controller'=>'requests','action'=>'update',$cart->product->id)));?>
And then later:
public function update($productId) {
// ...
$carrinho = $session->read('carrinho');
$quantidade = $this->request->data('quantity');
if ($quantidade > 0) {
$carrinho[$productId] = $quantidade;
}
// ...

WP-JSON - Multi-endpoint - Re-occuring Foreach Error

I'm currently trying to build out a multi-endpoint system for WP-JSON between 4 websites, and most of the time it's fine, however sometimes when my page performs the process, it will throw back an error for the Foreach cycle, saying 'Warning: Invalid argument supplied for foreach() in ...'
I've tried alternative methods of merging the arrays before retrieving the body using wp_remote_retrieve_body but there's no such luck. I've looked up various google solutions on multiple-endpoints using php but nothing i've found seems to do an effective job
<?php
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
/* BASE DETAILS FOR SEARCH*/
$b_url = get_site_url(); // Base URL
$posts_merged;
$args = array(
'sslverify' => false
);
if($_GET['search'] or !empty($_GET['search'])){
$filter_query = '?search='.$_GET['search'];
}else{
$filter_query = '';
}
$post_url_collective = array(
$b_url.'/wp-json/wp/v2/posts'.$filter_query, // Main Site
$b_url.'/db/wp-json/wp/v2/posts'.$filter_query, // DB Site
$b_url.'/dc/wp-json/wp/v2/posts'.$filter_query, // DC Site
$b_url.'/fw/wp-json/wp/v2/posts'.$filter_query // FW Site
);
$post_response = wp_remote_get($post_url_collective[0], $args);
$post_response = wp_remote_retrieve_body($post_response);
$post_response = json_decode($post_response);
$post_response_two = wp_remote_get($post_url_collective[1], $args);
$post_response_two = wp_remote_retrieve_body($post_response_two);
$post_response_two = json_decode($post_response_two);
$post_response_three = wp_remote_get($post_url_collective[2], $args);
$post_response_three = wp_remote_retrieve_body($post_response_three);
$post_response_three = json_decode($post_response_three);
$post_response_four = wp_remote_get($post_url_collective[3], $args);
$post_response_four = wp_remote_retrieve_body($post_response_four);
$post_response_four = json_decode($post_response_four);
$posts_merged = array_merge( $post_response, $post_response_two, $post_response_three, $post_response_four );
?>
<div class="container multi-search-wrap">
<div class="row" style="margin-bottom: 0px">
<div class="col sm12 m12 l12">
<form class="multi-search-form" method="GET">
<div class="row" style="margin-bottom: 0px">
<div class="col sm8 m9 l10">
<input type="text" name="search" value="<?php echo ( isset( $_GET['search'] ) ? $_GET['search'] : '' ); ?>" placeholder="Search for..."/>
</div>
<div class="col sm4 m3 l2">
<input type="submit" value="Search" />
</div>
</div>
</form>
</div>
</div>
<div class="row" style="background: #eeeeee;padding: 10px;font-size: 12px;margin:0px 0px 20px 0px">
<div class="col sm12 m12 l12">
We've found <strong><?php echo count($posts_merged);?></strong> results for <?php echo $_GET['search'];?>...
</div>
</div>
<div class="row">
<?php
// Post Loop
foreach($posts_merged as $get_post) {
$image_url = $b_url.'/wp-json/wp/v2/media/'.$get_post->featured_media;
$image_response = wp_remote_get($image_url, $args);
$image_response = json_decode($image_response['body']);
//echo'<pre>';print_r($image_response);echo'</pre>';
echo '<div class="col sm12 m6 l6 multi-search-post">';
echo '<div class="row">';
echo '<div class="col sm12 m3 l4 multi-search-post">';
if(!empty($image_response->media_details->sizes->thumbnail->source_url)){
echo '<img class="img_'.$get_post->id.'" src="'.$image_response->media_details->sizes->thumbnail->source_url.'" width="auto"><br>';
}else{
echo '<img class="img_'.$get_post->id.'" src="'.get_template_directory_uri().'/images/post-placeholder.jpg" width="auto"><br>';
}
echo '</div>';
echo '<div class="col sm12 m9 l8 multi-search-post">';
echo '<a href="'.$get_post->link.'">';
echo '<h3>'.$get_post->title->rendered.'</h3>';
echo '</a>';
echo '<p>'.limit_text($get_post->excerpt->rendered, 30).'</p>';
echo '</div>';
echo '</div>';
echo '</div>';
}
?>
</div>
</div>
I would like to improve the load speed of the queries but the most important part is ridding this occassional Foreach error.
Any help would be greatly appreciated

Categories