How to parse Hypertable data using php - hypertable

I have inserted data's in Hypertable. But i don't know, how to get particular value from result. My PHP thrift code is :
$GLOBALS['THRIFT_ROOT'] = "/opt/hypertable/0.9.5.6/lib/php";
require_once $GLOBALS['THRIFT_ROOT'].'/ThriftClient.php';
$client = new Hypertable_ThriftClient("localhost", 38080);
$namespace = $client->namespace_open("appuniv");
$query = "select * from category_details limit 1";
$tab = $client->hql_query($namespace, $query);
var_dump($tab);
I'm getting the below result :
object(Hypertable_ThriftGen_HqlResult)#24 (4) { ["results"]=> NULL
["cells"]=> array(2) { [0]=> object(Hypertable_ThriftGen_Cell)#25 (2)
{ ["key"]=> object(Hypertable_ThriftGen_Key)#26 (6) { ["row"]=>
string(32) "077262cc53a1fb1b5f651d31b6bf81ba" ["column_family"]=>
string(8) "category" ["column_qualifier"]=> string(4) "name"
["timestamp"]=> float(1.3419935154984E+18) ["revision"]=>
float(1.3419935154984E+18) ["flag"]=> int(255) } ["value"]=> string(7)
"Medical" } [1]=> object(Hypertable_ThriftGen_Cell)#27 (2) { ["key"]=>
object(Hypertable_ThriftGen_Key)#28 (6) { ["row"]=> string(32)
"077262cc53a1fb1b5f651d31b6bf81ba" ["column_family"]=> string(8)
"category" ["column_qualifier"]=> string(4) "type" ["timestamp"]=>
float(1.3419935154984E+18) ["revision"]=> float(1.3419935154984E+18)
["flag"]=> int(255) } ["value"]=> string(7) "android" } }
["scanner"]=> NULL ["mutator"]=> NULL } 0.9678
May i know how to get the ["value"]=> string(7) "Medical" value from above result.

/**
* Sort result by column family/qualifier
* #param thrift result
*/
private function sort($data)
{
$result = array();
foreach ($data as $cell)
{
$row = $cell->key->row;
if (!isset($result[$row])) {
$result[$row] = new stdClass;
$result[$row]->row = $cell->key->row;
foreach ($this->columns as $col) {
$pos = strpos($col, ':') ;
$qualifier = ($pos) ? substr($col, $pos + 1) : NULL;
$col = !$pos ? $col : substr($col, 0, $pos);
if (!$qualifier)
$result[$row]->{$col} = NULL;
else if ($qualifier[0] != '/')
$result[$row]->{$col}[$qualifier] = NULL;
}
}
$result[$row]->{$cell->key->column_family}[$cell->key->column_qualifier] = $cell->value;
}
return $result;
}

Related

Trying to get property 'parameter' of non-object

Hello i have an api in Laravel i'm trying to get a value from a table column
Json response it already in the table json response but when i get it its says:
Trying to get property 'parameter' of non-object
i'm so new on laravel so i'm really lost with this
The Function i use when i call the api
it go to
$parameter = $value->parameter;
And then stop and say in PriceDetailHolder():
Trying to get property 'parameter' of non-object
I showed 2 functions because i don't really know where is the problem exactly
public static function PriceDetailHolder($booking_prices, $booking_id = null, $currency = null): array
{
if (!empty($booking_id) && $booking_id !== null) {
/**
* #var $booking Booking
*/
$booking = Booking::query()->find($booking_id);
$currency = $booking->CountryArea->Country->isoCode;
}
$holder[] = [
'highlighted_text' => trans('admin.message665'),
'highlighted_text_color' => '333333',
'highlighted_style' => 'BOLD',
'highlighted_visibility' => true,
'small_text' => 'eee',
'small_text_color' => '333333',
'small_text_style' => '',
'small_text_visibility' => false,
'value_text' => trans('admin.message665'),
'value_text_color' => '333333',
'value_text_style' => '',
'value_textvisibility' => false
];
foreach ($booking_prices as $key => $value) {
$code = '';
if (!empty($value->code)) {
$code = "({$value->code})";
}
$parameter = $value->parameter;
/**
* #var $parameterDetails PricingParameter
*/
$parameterDetails = PricingParameter::query()->find($parameter);
if ($parameterDetails === null) {
$prameterName = $parameter;
} else {
if ((int)$parameterDetails->parameterType === 13) {
$applicable = (int)$parameterDetails->applicable === 1 ? trans('api.message174') : trans('api.message175');
/**
* #var $priceCardValue PriceCardValue
*/
$priceCardValue = PriceCardValue::query()->where([['price_card_id', '=', $value->price_card_id], ['pricing_parameter_id', '=', $parameter]])->first();
$code = "($priceCardValue->parameter_price %)\n" . $applicable;
}
$prameterName = $parameterDetails->ParameterApplication . $code;
}
$holder[] = [
'highlighted_text' => $prameterName,
'highlighted_text_color' => '333333',
'highlighted_style' => 'NORMAL',
'highlighted_visibility' => true,
'small_text' => 'eee',
'small_texot_clor' => '333333',
'small_text_style' => '',
'small_text_visibility' => false,
'value_text' => $currency . ' ' . $value->amount,
'value_text_color' => '333333',
'value_text_style' => '',
'value_textvisibility' => true
];
}
return $holder;
}
public function End(EndTripRequest $request)
{
$merchant_id = $request->user('api-driver')->merchant_id;
$validator = Validator::make($request->all(), [
'booking_id' => [
'required',
'integer',
Rule::exists('bookings', 'id')->where(static function ($query) {
$query->where('booking_status', TripStatus::STARTED);
}),
],
'latitude' => 'required',
'longitude' => 'required',
'tip_amount' => 'nullable|numeric',
]);
if ($validator->fails()) {
$errors = $validator->messages()->all();
return response()->json(['result' => '0', 'message' => $errors[0], 'data' => []]);
}
/**
* #var $configuration BookingConfiguration
*/
$configuration = BookingConfiguration::query()->where('merchant_id', $merchant_id)->first();
$booking_id = $request->booking_id;
/**
* #var $booking Booking
*/
$booking = Booking::with('PriceCard')->find($booking_id);
/**
* #var $bookingDetails BookingDetail
*/
$bookingDetails = BookingDetail::booking($booking_id)->first();
$service_type_id = (int)$booking->service_type_id;
if (!in_array($service_type_id, [1, 5], false)) {
$start_meter_value = $bookingDetails->start_meter_value;
$customMessages = [
'gt' => trans_choice('api.endmeter', 3, ['value' => $start_meter_value]),
];
$validator = Validator::make($request->all(), [
'send_meter_image' => 'required',
'send_meter_value' => 'required|integer|gt:' . $start_meter_value,
], $customMessages);
if ($validator->fails()) {
$errors = $validator->messages()->all();
return response()->json(['result' => '0', 'message' => $errors[0], 'data' => []]);
}
}
$request->user('api-driver')->free_busy = 2;
$request->user('api-driver')->total_trips += 1;
$request->user('api-driver')->save();
/**
* #var $user \App\User
*/
$user = $booking->User;
++$user->total_trips;
$user->save();
if ($request->hasFile('send_meter_image')) {
$bookingDetails->end_meter_value = $request->send_meter_value;
$request->file('send_meter_image');
$send_meter_image = $request->send_meter_image->store('service');
$bookingDetails->end_meter_image = $send_meter_image;
}
$pricing_type = $booking->PriceCard->pricing_type;
$price_card_id = $booking->price_card_id;
$key = $configuration->google_key;
$endAddress = GoogleController::GoogleLocation($request->latitude, $request->longitude, $key);
$endAddress = $endAddress ?: 'Address Not found';
$endTimeStamp = time();
$bookingDetails->end_timestamp = $endTimeStamp;
$bookingDetails->end_latitude = $request->latitude;
$bookingDetails->end_longitude = $request->longitude;
$bookingDetails->end_location = $endAddress;
$bookingDetails->accuracy_at_end = $request->accuracy;
$bookingDetails->save();
$start_timestamp = $bookingDetails->start_timestamp;
$seconds = $endTimeStamp - $start_timestamp;
$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
//$secs = floor($seconds % 60);
$timeFormat = sprintf('%02d H %02d M', $hours, $mins);
$rideTime = round(abs($endTimeStamp - $start_timestamp) / 60, 2);
$from = $bookingDetails->start_latitude . ',' . $bookingDetails->start_longitude;
$to = $request->latitude . ',' . $request->longitude;
$coordinates = '';
$bookingData = new BookingDataController();
$bookingData->ActivateRefer($booking->id);
/**
* Calculate the distance based on service type.
*/
switch ($service_type_id) {
case '1':
$bookingcoordinates = BookingCoordinate::query()->where('booking_id', $request->booking_id)->first();
$pick = $booking->pickup_latitude . ',' . $booking->pickup_longitude;
$drop = $booking->drop_latitude . ',' . $booking->drop_longitude;
$distanceCalculation = new DistanceCalculation();
$distance = $distanceCalculation->distance($from, $to, $pick, $drop, $bookingcoordinates['coordinates'], $merchant_id, $key);
$distance = round($distance);
$coordinates = $bookingcoordinates['coordinates'];
break;
case '5':
$distance = GoogleController::GoogleShortestPathDistance($from, $to, $key);
$distance = round($distance);
break;
default:
$distance = $bookingDetails->end_meter_value - $bookingDetails->start_meter_value;
$distance *= 1000;
}
/**
* Calculate Trip Amount based on Pricing Type
*/
switch ($pricing_type) {
case '1':
case '2':
$newArray = PriceController::CalculateBill($price_card_id, $distance, $rideTime, $booking_id, $bookingDetails->wait_time, (double)$bookingDetails->dead_milage_distance, (double)$booking->User->outstanding_amount);
/**
* Check if trip went through a toll gate
*/
if (!empty($configuration->toll_api)) {
$newTool = new Toll();
$toolPrice = $newTool->checkToll($configuration->toll_api, $from, $to, $coordinates, $configuration->toll_key);
if (is_array($toolPrice) && array_key_exists('cost', $toolPrice) && $toolPrice['cost'] > 0) {
$parameter[] = ['price_card_id' => $price_card_id, 'booking_id' => $booking_id, 'parameter' => 'TollCharges', 'amount' => sprintf('%0.2f', $toolPrice['cost']), 'type' => 'CREDIT', 'code' => ''];
$newArray[] = $parameter;
}
}
$newExtraCharge = new ExtraCharges();
$carditnewArray = array_filter($newArray, static function ($e) {
return ($e['type'] === 'CREDIT');
});
$amount = array_sum(Arr::pluck($carditnewArray, 'amount'));
if ($booking->number_of_rider > 1) {
$amount += $booking->PriceCard->extra_sheet_charge;
}
$booking_time = (int)$booking->booking_type === BookingType::RIDE_NOW ? $booking->created_at->toTimeString() : $booking->later_booking_time;
$timeCharge = $newExtraCharge->NightChargeEstimate($price_card_id, $booking_id, $amount, $booking_time);
if (!empty($timeCharge)) {
$charge = array_sum(Arr::pluck($timeCharge, 'amount'));
$amount += $charge;
$newArray = array_merge($newArray, $timeCharge);
}
/**
* Check and calculate surge price
*/
if ((int)$booking->PriceCard->sub_charge_status === 1) {
$surge = (int)$booking->PriceCard->sub_charge_type === 1 ? $booking->PriceCard->sub_charge_value : bcdiv($amount, $booking->PriceCard->sub_charge_value, 2);
$amount += $surge;
$parameter = ['price_card_id' => $price_card_id, 'booking_id' => $booking_id, 'parameter' => 'Surge-Charge', 'amount' => sprintf('%0.2f', $surge), 'type' => 'CREDIT', 'code' => ''];
$newArray[] = $parameter;
}
$discoutArray = array_filter($newArray, static function ($e) {
return ($e['type'] === 'DEBIT');
});
/**
* Check if there's a promo code applied to this booking
*/
if (!empty($discoutArray)) {
$promoDiscount = sprintf('%0.2f', array_sum(Arr::pluck($discoutArray, 'amount')));
$bookingDetails->promo_discount = $promoDiscount;
$amount = $amount > $promoDiscount ? $amount - $promoDiscount : '0.00';
} else {
$bookingDetails->promo_discount = '0.00';
}
/**
* Check if a driver or user is referee
*/
$referDiscount = $bookingData->Refer($booking->user_id);
if ($referDiscount !== NULL) {
switch ($referDiscount->offer_type) {
case '1':
$referAmount = $amount;
$amount = 0;
break;
case '2':
$referAmount = ($amount * $referDiscount->referral_offer_value) / 100;
$amount -= $referAmount;
break;
case '3':
$referAmount = $referDiscount->referral_offer_value;
$amount = $amount < $referAmount ? 0 : $amount - $referAmount;
break;
default:
$referAmount = 0;
break;
}
$parameter[] = ['price_card_id' => $price_card_id, 'booking_id' => $booking_id, 'parameter' => 'Promotion', 'amount' => sprintf('%0.2f', $referAmount), 'type' => 'DEBIT', 'code' => ''];
array_push($newArray, $parameter);
}
$billDetails = json_encode($newArray);
$bookingDetails->total_amount = sprintf('%0.2f', $amount);
$payment = new Payment();
if ($amount > 0) {
$payment->MakePayment($booking->id, $booking->payment_method_id, $amount, $booking->user_id, $booking->card_id);
} else {
$payment->UpdateStatus($booking->id);
}
$bookingDetails->bill_details = $billDetails;
$bookingDetails->save();
\App\Http\Controllers\Helper\CommonController::Commission($booking_id, $amount);
if ($booking->User->outstanding_amount) {
User::query()->where('id', $booking->user_id)->update(['outstanding_amount' => NULL]);
}
break;
case '3':
$amount = '';
break;
default:
$amount = '';
break;
}
if ($service_type_id === 5) {
$poolRide = new PoolController();
$poolRide->DropPool($booking, $request);
}
$distance = round($distance / 1000, 2) . ' Km';
$booking->booking_status = TripStatus::COMPLETED;
$booking->travel_distance = $distance;
$booking->travel_time = $timeFormat;
$booking->travel_time_min = $rideTime;
$booking->final_amount_paid = sprintf('%0.2f', $amount);
$booking->save();
$user_id = $booking->user_id;
$message = 'Driver End Ride';
$userdevices = UserDevice::getLastDevice($booking->user_id);
$playerids = [$userdevices->player_id];
$data = $bookingData->BookingNotification($booking);
Onesignal::UserPushMessage($playerids, $data, $message, 1, $booking->merchant_id);
return response()->json(['result' => '1', 'message' => trans('api.message15'), 'data' => $booking]);
}
Its coming from a table
[{"price_card_id":3,"booking_id":"42540","parameter":1,"amount":"1.50","type":"CREDIT","code":""},{"price_card_id":3,"booking_id":"42540","parameter":2,"amount":"0.00","type":"CREDIT","code":""},{"price_card_id":3,"booking_id":"42540","parameter":3,"amount":"0.00","type":"CREDIT","code":""},{"price_card_id":3,"booking_id":"42540","parameter":4,"amount":"0.00","type":"CREDIT","code":""},{"price_card_id":3,"booking_id":"42540","parameter":5,"amount":"0.00","type":"DEBIT","code":""},[{"price_card_id":3,"booking_id":"42540","parameter":"Promotion","amount":10,"type":"DEBIT","code":""}]]
Please tell me to show you anything if i'm wrong i'm really sorry for my poor knowledge in all this but i'm just in the first step to learn
So a quick look at your code the code that fails is $value->parameter.
That value comes from $booking_prices, so the issue lies in the objects returned when iterating booking_prices does not have the property parameter.
You could remove the error by doing $parameter = $value->parameter ?? null; // null as default value or by figuring out why the parameter attribute does not always exist.

Yii 2 Get NULL when select data with where in array

I have an array $areaID :
array(3) {
[0]=> array(1) { ["idarea"]=> int(56) }
[1]=> array(1) { ["idarea"]=> int(67) }
[2]=> array(1) { ["idarea"]=> int(116)}
}
Then, I want to select from MySQL database to get data where $areaID in array. My query:
$data = (new \yii\db\Query())
->select('*')
->from('store')
->join('LEFT JOIN','detail_area','detail_area.idareaV = store.idareas')
->join('LEFT JOIN','detail_user','detail_user.id_area = detail_area.idarea')
->where(['in','detail_area.idarea',$areaID])
->all()
But when running,, i got my $areaID is null. Like this :
SELECT * FROM `store` LEFT JOIN `detail_area` ON detail_area.idareaV = store.idareas LEFT JOIN `detail_user` ON detail_user.id_area = detail_area.idarea WHERE (`detail_area`.`idarea` IN (NULL, NULL, NULL))
Can you help me? Thank you ...
Use
->where([
'detail_area.idarea' => array_values(
\yii\helpers\ArrayHelper::map($areaID, 'idarea', 'idarea')
)
])

Somehow can't prevent name duplication

I recently ran into some trouble with my registration system, I've tried to prevent name duplication in a lot of ways, And already browsed stackoverflow aswell.
But i can't seem to find the solution.
Here is my code
<?php
if (isset($_POST['registerBtn']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
$errors = array();
$checkUsername = $odb -> prepare("SELECT COUNT(*) as total from FROM `users` WHERE `username` = :username");
$checkUsername -> execute(array(':username' => $username));
$countUsername = $checkUsername -> fetchColumn(0);
if ($checkUsername > 0)
{
$errors['Username is already taken'];
}
if (!ctype_alnum($username) || strlen($username) < 4 || strlen($username) > 15)
{
$errors[] = 'Username Must Be Alphanumberic And 4-15 characters in length';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$errors[] = 'Email is invalid';
}
if (empty($username) || empty($password) || empty($rpassword) || empty($email))
{
$errors[] = 'Please fill in all fields';
}
if ($password != $rpassword)
{
$errors[] = 'Passwords do not match';
}
if (empty($errors))
{
$insertUser = $odb -> prepare("INSERT INTO `users` VALUES(NULL, :username, :password, :email, 0, 0, 0, 0)");
$insertUser -> execute(array(':username' => $username, ':password' => SHA1($password), ':email' => $email));
echo '<div class="nNote nSuccess hideit"><p><strong>SUCCESS: </strong>User has been registered. Redirecting....</p></div><meta http-equiv="refresh" content="3;url=login.php">';
}
else
{
echo '<div class="nNote nFailure hideit"><p><strong>ERROR:</strong><br />';
foreach($errors as $error)
{
echo '-'.$error.'<br />';
}
echo '</div>';
}
}
?>
You can put a UNIQUE constraint on username as such:
CREATE TABLE users
(
id int NOT NULL AUTO_INCREMENT,
username varchar(30),
password varchar(80),
email varchar(80),
PRIMARY KEY (id),
UNIQUE KEY username (username)
)
You should be comparing to $countUsername, not $checkUsername.
if ($checkUsername > 0)
Change to
if ($countUsername> 0)
Also, this line should be changed from:
if ($checkUsername > 0)
{
$errors['Username is already taken'];
}
To
if ($checkUsername > 0)
{
$errors[] = 'Username is already taken';
}
See below:
<?php
if (isset($_POST['registerBtn']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
$errors = array();
$checkUsername = $odb -> prepare("SELECT COUNT(*) as total from FROM `users` WHERE `username` = :username");
$checkUsername -> execute(array(':username' => $username));
$countUsername = $checkUsername -> fetchColumn(0);
$errors = [];
if ($countUsername > 0)
{
$errors[] = 'Username is already taken';
}
if (!ctype_alnum($username) || strlen($username) < 4 || strlen($username) > 15)
{
$errors[] = 'Username Must Be Alphanumberic And 4-15 characters in length';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$errors[] = 'Email is invalid';
}
if (empty($username) || empty($password) || empty($rpassword) || empty($email))
{
$errors[] = 'Please fill in all fields';
}
if ($password != $rpassword)
{
$errors[] = 'Passwords do not match';
}
if (count($errors) > 0)
{
$insertUser = $odb -> prepare("INSERT INTO `users` VALUES(NULL, :username, :password, :email, 0, 0, 0, 0)");
$insertUser -> execute(array(':username' => $username, ':password' => SHA1($password), ':email' => $email));
echo '<div class="nNote nSuccess hideit"><p><strong>SUCCESS: </strong>User has been registered. Redirecting....</p></div><meta http-equiv="refresh" content="3;url=login.php">';
}
else
{
echo '<div class="nNote nFailure hideit"><p><strong>ERROR:</strong><br />';
foreach($errors as $error)
{
echo '-'.$error.'<br />';
}
echo '</div>';
}
}
?>

How to create JSON array within a JSON array

3 tables in MYSQL
table_product - product_id, product_name
table_variane - variant_id, variant_name
table_product_variants - product_id, variant_id, MRP, SellPrice
I want to create JSON data out of those in Perl for all the products, in this format:
[
{
"ProductID": "1",
"ProductName": "Green Detergent Bar",
"Variants": [
{
"VariantID": "1",
"VariantName": "500GM",
"MRP": "20.00",
"SellPrice": "19.50"
},
{
"VariantID": "2",
"VariantName": "1KG",
"MRP": "40.00",
"SellPrice": "38.00"
}
]
},
{
"ProductID": "2",
"ProductName": "ABCD",
"Variants": [
{
"VariantID": "3",
"VariantName": "1KG",
"MRP": "200.00",
"SellPrice": "190.50"
},
{
"VariantID": "2",
"VariantName": "1KG",
"MRP": "40.00",
"SellPrice": "38.00"
}
]
}
]
This is Perl Code
my $sql_query = ""; //need to fill this.
my $statement = $db_handle->prepare ($sql_query) or die "Couldn't prepare query '$sql_query': $DBI::errstr\n";
$statement->execute() or die "SQL Error: $DBI::errstr\n";
my #loop_data = ();
while (my #data = $statement->fetchrow_array())
{
my %data = //need to fill this too.
push(#loop_data, \%data);
}
my $json_text = to_json(\#loop_data);
print $json_text;
Please help in filling SQL query and while loop.
Its just a blueprint. Any modification in code is also fine.
That you need arrays (not hashes) complicates things a bit.
Option 1
Use two queries, one that finds the products, and one that finds the variants of a product.
my $product_sth = $dbh->prepare("
SELECT product_id,
product_name
FROM table_product
");
my $variant_sth = $dbh->prepare("
SELECT tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product_variants AS tpv
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
WHERE tpv.product_id = ?
");
my #data;
while (my $product_row = $product_sth->fetchrow_hashref()) {
my #variants;
$variant_sth->execute($product_row->{product_id});
while (my $variant_row = $variant_sth->fetchrow_hashref()) {
push #variants, {
VariantID => $variant_row->{variant_id},
VariantName => $variant_row->{variant_name},
MRP => $variant_row->{MRP},
SellPrice => $variant_row->{SellPrice},
};
}
push #data, {
ProductID => $product_row->{product_id},
ProductName => $product_row->{product_name},
Variants => \#variants,
};
}
my $data_json = to_json(\#data);
Option 2
Use an HoA to group the variants of a product when using a single query.
my $sth = $dbh->prepare("
SELECT tp.product_id,
tp.product_name,
tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product AS tp
JOIN table_product_variants AS tpv
ON tp.product_id = tpv.product_id
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
");
my %data;
while (my $row = $sth->fetchrow_hashref()) {
my $product_id = $row->{product_id};
my $product = $data{$product_id} ||= {
ProductID => $row->{product_id},
ProductName => $row->{product_name},
Variants => [],
};
push #{ $product->{Variants} }, {
VariantID => $row->{variant_id},
VariantName => $row->{variant_name},
MRP => $row->{MRP},
SellPrice => $row->{SellPrice},
};
}
my $data_json = to_json([ values(%data) ]);
Option 3
Use sorting to group the variants of a product when using a single query.
my $sth = $dbh->prepare("
SELECT tp.product_id,
tp.product_name,
tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product AS tp
JOIN table_product_variants AS tpv
ON tp.product_id = tpv.product_id
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
ORDER BY tp.product_id
");
my $last_product_id = 0;
my #data;
while (my $row = $sth->fetchrow_hashref()) {
my $product_id = $row->{product_id};
if ($product_id != $last_product_id) {
$last_product_id = $product_id;
push #data, {
ProductID => $row->{product_id},
ProductName => $row->{product_name},
Variants => [],
};
}
push #{ $data[-1]{Variants} }, {
VariantID => $row->{variant_id},
VariantName => $row->{variant_name},
MRP => $row->{MRP},
SellPrice => $row->{SellPrice},
};
}
my $data_json = to_json(\#data);
It's a little extra work than option 2, but it has the smallest client-side memory footprint (if you didn't have to keep everything in memory).

Insert data with insert_batch

I'm using the following statement to insert data in mysql with codeigniter.
$this->db->insert_batch($table, $query);
$query is generated dynamically can have different number of columns on each array element
and maybe the number of elements may differ on condition
array (
0 => array(
'column1'=>'insert1',
'column2'=>'insert2'
),
1 => array(
'column1'=>'insert1';
'column2'=>'insert2',
'column4'=>'insert4'
)
)
could this cause an error or handles codigniter from deafult?
I'm building up the query as it follows
foreach ($sql_xml as $children) {
$children = $this->xml2array($children);
foreach ($children as $index => $child) {
if ($child != 'feed_id') {
$keys[$index] = $child;
}
}
}
switch (strtolower($this->config[0]->affiliate)) {
case 'case1':
$target_xml = $target_xml->productItems;
break;
case 'case2':
$target_xml = $target_xml;
break;
default :
break;
}
$query = array();
$data = array();
foreach ($target_xml as $feeds) {
$feeds = $this->xml2array($feeds);
$columns = new RecursiveIteratorIterator(new RecursiveArrayIterator($feeds));
foreach ($columns as $index => $column) {
if (array_key_exists($index, $keys)) {
if($column != ''){
$data[$keys[$index]] = $column;
$data['feed_id'] = $this->id;
}
//*TODO //$data['affiliate'] = "'.$this->config[0]->affiliate.'";
}
}
$query[] = $data;
}
if (count($query > 0)) {
foreach ($query as $t){
$this->db->insert($table, $t);
}
}
The array's would need to have the same amount of "columns".
So what I would recommend is the following (setting certain columns to null if no there is no data):
array (
0 => array(
'column1' => 'insert1',
'column2' => 'insert2',
'column3' => null,
'column4' => null
),
1 => array(
'column1' => 'insert1',
'column2' => 'insert2',
'column3' => 'insert3',
'column4' => 'insert4'
)
)
Also, your syntax is invalid and it would cause an error since you are using a ; instead of an , on the first column insert.