Error on update elasticsearch php "document_missing_exception" - php

I'm using Elasticsearch with PHP and after the required data mapping. I inserted the data via insert function as seen below:
public function insertNode ($event_id) {
global $conn1;
$client = $this->elasticclient;
$params = null;
$stmt = "SELECT
events.event_id,
events.event_title,
events.event_details,
DATE_FORMAT(events.added_date,'%d-%m-%Y') AS added_date
FROM events
WHERE events.event_id = $event_id";
$query = $conn1->prepare($stmt);
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$params = [
'index' => 'eventree',
'type' => 'events',
'id' => $row['event_id'],
'body' => [
'EVENT_TITLE' => $row['event_title'],
'EVENT_DETAILS' => $row['event_details'],
'START_TIME' => $row['start_time'],
'ADDED_DATE' => $row['added_date'],
'STATUS' => $row['status']
]
];
}
$responses = $client->index($params);
return true;
}
below you can see how I update data:
public function updateNode($event_id) {
global $conn1;
$client = $this->elasticclient;
$params = null;
$stmt = "SELECT
events.event_id,
events.event_title,
events.event_details,
events.status,
DATE_FORMAT(events.added_date,'%d-%m-%Y') AS added_date
FROM events
WHERE events.event_id = $event_id";
$query = $conn1->prepare($stmt);
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$params = [
'index' => 'eventree',
'type' => 'events',
'id' => $row['event_id'],
'body' => [
'doc' => [
'EVENT_TITLE' => $row['event_title'],
'EVENT_DETAILS' => $row['event_details'],
'START_TIME' => $row['start_time'],
'ADDED_DATE' => $row['added_date'],
'STATUS' => $row['status']
]]];
}
$responses = $client->update($params);
return true;
}
The problem is that the update process won't accept ids larger than 9, although there are records with ids greter than number 9. This is the error I get after running the update proccess:
{
"error": "{\"error\":{\"root_cause\":[{\"type\":\"document_missing_exception\",\"reason\":\"[events][10]: document missing\",\"index_uuid\":\"6l5vWeLLSb6CvcCsqTws9g\",\"shard\":\"1\",\"index\":\"eventree\"}],\"type\":\"document_missing_exception\",\"reason\":\"[events][10]: document missing\",\"index_uuid\":\"6l5vWeLLSb6CvcCsqTws9g\",\"shard\":\"1\",\"index\":\"eventree\"},\"status\":404}"
}

Your php code is wrong, you loop $rows and override $params variable all the time!

the correct code
public function insertNode($event_id) {
global $conn1;
$client = $this->elasticclient;
$params = null;
$stmt = "SELECT
events.event_id,
events.event_title,
events.event_details,
DATE_FORMAT(events.added_date,'%d-%m-%Y') AS added_date
FROM events
WHERE events.event_id = $event_id";
$query = $conn1->prepare($stmt);
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$params = [
'index' => 'eventree',
'type' => 'events',
'id' => $row['event_id'],
'body' => [
'EVENT_TITLE' => $row['event_title'],
'EVENT_DETAILS' => $row['event_details'],
'START_TIME' => $row['start_time'],
'ADDED_DATE' => $row['added_date'],
'STATUS' => $row['status']
]];
$responses = $client->index($params);
}
return true;
}
public function updateNode($event_id) {
global $conn1;
$client = $this->elasticclient;
$params = null;
$stmt = "SELECT
events.event_id,
events.event_title,
events.event_details,
events.status,
DATE_FORMAT(events.added_date,'%d-%m-%Y') AS added_date
FROM events
WHERE events.event_id = $event_id";
$query = $conn1->prepare($stmt);
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$params = [
'index' => 'eventree',
'type' => 'events',
'id' => $row['event_id'],
'body' => [
'doc' => [
'EVENT_TITLE' => $row['event_title'],
'EVENT_DETAILS' => $row['event_details'],
'START_TIME' => $row['start_time'],
'ADDED_DATE' => $row['added_date'],
'STATUS' => $row['status']
]]];
$responses = $client->update($params);
}
return true;
}

Related

Create json with php from all data from the database

I want to create json which contains all orders from datebase. I tried to write this code but it returns only one order.
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders =[
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
Now the response looks like this:
But I want like this:
Append to the $orders array:
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders[] =[ // <--- The difference
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;

Woocommerce rest api update product image gives error

I want to update my product with product image but it is not updated. I am using woocommerce rest API for adding a product.
I am following these step for update product:
Create a view file for display all the product list
Create edit function in the controller for getting all product data
when uploading a new image from edit form it gives an error
Here is my code:
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name=$image->getClientOriginalName();
$image->move('C:/xampp/htdocs/New-flex/wp-content/uploads/backend-product-image', $name);
$productimg_path_store_db = "http://localhost/New-flex/wp-content/uploads/backend-product-image/";
$productimg_allimg[] = $productimg_path_store_db.$name;
}
}
$AddContentText = $request->get('AddContentText');
if (!empty($AddContentText)) {
/* For List All product qnumber check in array */
$newallproducts_data = $woocommerce->get('products',array('per_page' => 100));
$array = json_decode(json_encode($newallproducts_data), True);
$partssku = array();
$partid = array();
$parturl = array();
foreach ($array as $key ) {
$partssku[] = $key['sku'];
$partid[] = $key['id'];
$parturl[] = $key['permalink'];
}
/* Create associative array product id and sku for compare */
$comb = array_combine($partssku,$partid);
/* Combine content QNUMBER and QTY in array */
$chunks = array_chunk(preg_split('/(;|,)/', $AddContentText), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
/*Product qnumber allready avilabale array*/
$diff = array_intersect_key($result,$comb);
/*NEW PRODUCT array*/
$newproduct = array_diff($result, $diff);
/* Qnumber insert in database */
$parts_name = implode(',', array_keys($result));
/* count insert in database */
$noofpartsuse = implode(',', array_values($result));
/*echo "<pre>";
echo "main data";
print_r($result);
echo "allproduct array";
print_r($comb);
echo "Product qnumber allready avilabale";
print_r($diff);
echo "NEW PRODUCT";
print_r($newproduct);
echo "</pre>";*/
// print_r($newproduct_data);
//print_r($woocommerce->post('products', $data));
}
else{
$parts_name = '';
$noofpartsuse = '';
}
$productactive = $request->get('productactive');
if(!empty($productactive))
{
$productactive = "publish";
}
else{
$productactive = "draft";
}
$ProductListOrder = $request->get('ProductListOrder');
$producttype = $request->get('producttype');
$ProductQNumber = $request->get('ProductQNumber');
$ProductName = $request->get('name');
$ProductWidthMM = $request->get('ProductWidthMM');
$ProductLengthMM = $request->get('ProductLengthMM');
$ProductWidthInch = $request->get('ProductWidthInch');
$ProductLengthInch = $request->get('ProductLengthInch');
$Productinfotext = $request->get('Productinfotext');
$Producttechnocaldesc = $request->get('Producttechnocaldesc');
$metadescription = $request->get('metadescription');
$proimgalt = $request->get('proimg-alt');
$proyoutubelink = $request->get('proyoutubelink');
$proyoutubelinkalt = $request->get('proyoutubelink-alt');
$provimeolink = $request->get('provimeolink');
$provimeolinkalt = $request->get('provimeolink-alt');
$onshapelink = $request->get('onshapelink');
$onshapelinkalt = $request->get('onshapelink-alt');
$data = [
'name' => $ProductName,
'type' => $producttype,
'status' => $productactive,
'regular_price' => '',
'description' => $Productinfotext,
'short_description' => $Producttechnocaldesc,
'sku' => $ProductQNumber,
'categories' =>array (),
'meta_data' => [
[
'key' => 'list_order',
'value' => $ProductListOrder
],
[
'key' => 'ProductWidthMM',
'value' => $ProductWidthMM
],
[
'key' => 'ProductLengthMM',
'value' => $ProductLengthMM
],
[
'key' => 'ProductWidthInch',
'value' => $ProductWidthInch
],
[
'key' => 'ProductLengthInch',
'value' => $ProductLengthInch
],
[
'key' => 'proyoutubelink',
'value' => $proyoutubelink
],
[
'key' => 'proyoutubelink-alt',
'value' => $proyoutubelinkalt
],
[
'key' => 'provimeolink',
'value' => $provimeolink
],
[
'key' => 'provimeolink-alt',
'value' => $provimeolinkalt
],
[
'key' => 'onshapelink',
'value' => $onshapelink
],
[
'key' => 'onshapelink-alt',
'value' => $onshapelinkalt
],
[
'key' => 'UseParts-link',
'value' => $parts_name
],
[
'key' => 'Noofparts-use',
'value' => $noofpartsuse
]
],
'images' => array ()
];
/* image array for store image */
if(!empty($productimg_allimg)){
$images = &$data['images'];
$n = 0;
foreach($productimg_allimg as $id)
{
$images[] = array( //this array must be created dynamic
'src' => $id,
'position' => $n++
);
}
unset($images);
}
if(!empty($_POST['categories'])){
/* Producta category array */
$categories = &$data['categories'];
foreach($_POST['categories'] as $cat)
{
$categories[] = array( //this array must be created dynamic
'id' => $cat
);
}
unset($categories);
}
$data_insert = $woocommerce->post('products', $data);
if($data_insert){
foreach ($newproduct as $key => $value) {
$newproduct_data = [
'name' => $key,
'sku' => $key
];
$woocommerce->post('products', $newproduct_data);
}
}
return redirect('products')->with('success', 'Product has been Added');
Above code written in laravel

PHP MVC query to get all existing rows is returning only 1 row

I have a working query but its only returning 1 row - where or what can I do to return all existing rows?
Model:
public function getInfo() {
$info_query = $this->db->query("SELECT * FROM `km_info` WHERE ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) AND status = '1'");
if ($info_query->num_rows){
return array(
'info_id' => $info_query->row['info_id'],
'name' => $info_query->row['name'],
'amount' => $info_query->row['amount'],
'date_start' => $info_query->row['date_start'],
'date_end' => $info_query->row['date_end'],
'status' => $info_query->row['status'],
'date_added' => $info_query->row['date_added']
);
}
}
Controller:
$info_options = $this->model_extension_total_info->getInfo();
if ($info_options){
$json['info_options'] = array();
$json['info_options'][] = array(
'info_id' => $info_options['info_id'],
'name' => $info_options['name'],
'amount' => $info_options['amount'],
'date_start' => $info_options['date_start'],
'date_end' => $info_options['date_end'],
'status' => $info_options['status'],
'date_added' => $info_options['date_added']
);
}
When I try foreach() in the controller, I still only get one row.:
foreach ($info_options as $info) {
var_dump($info_options['name']);exit;
//var_dump($info_options['name']); results: Warning: Illegal string offset 'name'
}
In the model, when I dump:
$info_query I get 9 -- which is all of the rows I'm expecting.
Not particularly certain what I'm missing or doing wrong.
You're not looping over the result. Not in model nor in the controller. Though I don't know why you'd do this twice. Maybe I'm just not understanding your code.
Model:
$data = [];
if ($info_query->num_rows){
foreach ($info_query->result() as $row) {
$data[] = array(
'info_id' => $row['info_id'],
'name' => $row['name'],
'amount' => $row['amount'],
'date_start' => $row['date_start'],
'date_end' => $row['date_end'],
'status' => $row['status'],
'date_added' => $row['date_added']
);
}
return $data;
}
Controller:
$info_options = $this->model_extension_total_info->getInfo();
$json['info_options'] = array();
if ($info_options){
foreach ($info_options as $info) {
$json['info_options'][] = array(
'info_id' => $info['info_id'],
'name' => $info['name'],
'amount' => $info['amount'],
'date_start' => $info['date_start'],
'date_end' => $info['date_end'],
'status' => $info['status'],
'date_added' => $info['date_added']
);
}
}
Technically, you don't have to loop at all. You can just:
public function getInfo() {
$info_query = $this->db->query("SELECT * FROM `km_info` WHERE ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) AND status = '1'");
if ($info_query->num_rows){
return $info_query->result();
}
else
{
return false;
}
}
and
$info_options = $this->model_extension_total_info->getInfo();
// and that's it, just do whatever you need with $info_options

PHP json_encode

This is my script at the moment:
//... PDO CONNECTION AND QUERY //...*
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){
$return[]=array('employeeid'=>$row['employeeid'],
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'id'=>$row['id'],
'startdate'=>$row['startdate'],
'enddate'=>$row['enddate'],
'type'=>$row['type'],
'reason'=>$row['reason']);
}
$dbh = null;
header('Content-type: application/json'); echo '' .
json_encode($return) .'';
This gives a result like:
[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'id': '001',
...,
...
}
]
[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'id': '002',
...,
...
}
]
But what i would like is a result like this (so each employee has one object with multiple requests):
[
{
'employeeid': '1',
'firstname': 'john',
'lastname': 'doe',
'requests': [
{
'id': '001',
...,
...
},
{
'id': '002',
...,
...
}
]
}
]
Can someone help me with this?
Thanks in advance,
Jan
You'll need to include the requests records in each employee array:
foreach ($result as $row){
$employee=array('employeeid'=>$row['employeeid'],
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'id'=>$row['id'],
'startdate'=>$row['startdate'],
'enddate'=>$row['enddate'],
'type'=>$row['type'],
'reason'=>$row['reason']);
$requests = $dbh->query(sprintf("SELECT * FROM employee_requests WHERE employee_id = '%s'", $row['employeeid']))->fetchAll(PDO::FETCH_ASSOC);
$employee['requests'] = requests;
$return[] = $employee;
}
Change your foreach as follows:
foreach ($result as $row){
$employeeid = $row['employeeid'];
if (!isset($return[$employeeid]))
$return[$employeeid] = array(
'employeeid' => $row['employeeid'],
'firstname' => $row['firstname'],
'lastname' => $row['lastname'],
'requests' => array()
);
$return[$employeeid]['requests'][] = array(
'id' => $row['id'],
'startdate' => $row['startdate'],
'enddate' => $row['enddate'],
'type' => $row['type'],
'reason' => $row['reason']
);
}

Looping through results of a sql query

I have a query that returns multiple rows. I can't seem to find a way to store the rows in the $params array. Is there a way to loop throw and store each row in the $params variable
$aResult = $db->exec_sql($sql);
$params = array(
// where $aResult[o]'' would be row 1 [1] row 2 etc. //
'store_id' => $aResult[]['iStoreID'],
'user_id' => $aResult[]['iUserID'],
'store_name' => $aResult[]['cStoreName'],
'store_url' => $aResult[]['cStoreURL'],
'rid' => $aResult[]['cRID'],
'affiliate_id' => $aResult[]['iAffiliateID'],
'team_id' => $aResult[]['iTeamID'],
'bizOP' => $aResult[]['cDefaultBizOpp'],
'showBizOPp' => $aResult[]['iShowBizOppDropdown'],
'boPosting' => $aResult[]['iEnableBOPosting'],
'brandinglevel' => $aResult[]['iBrandingLevel']
);
thank you for your help
As simple as that:
$params = array();
foreach($aResult as $row) {
$params[] = array(
'store_id' => $row['iStoreID'],
'user_id' => $row['iUserID'],
'store_name' => $row['cStoreName'],
'store_url' => $row['cStoreURL'],
'rid' => $row['cRID'],
'affiliate_id' => $row['iAffiliateID'],
'team_id' => $row['iTeamID'],
'bizOP' => $row['cDefaultBizOpp'],
'showBizOPp' => $row['iShowBizOppDropdown'],
'boPosting' => $row['iEnableBOPosting'],
'brandinglevel' => $row['iBrandingLevel']
);
}
Without knowing the exact structure of the result array i guess you need something like this:
<?php
$params = array();
$mapping = array(
'store_id' => 'iStoredID',
'user_id' => 'iUserID',
// and so on...
);
foreach ($aResult as $row) {
$tempRow = array();
foreach ($row as $key => $value) {
$paramKey = isset($mapping[$key]) ? $mapping[$key] : $key;
$tempRow[$paramKey] = $value;
}
$params[] = $tempRow;
}
I use it like this
$aResult = mysql_query($sql);
while($data = mysql_fetch_array($result)) {
'store_id' = $aResult['iStoreID'];
}
At least that is the idea

Categories