Related
I created a function for a custom field for a fee which also multiplies depending on the amount of people booking:
// Add Custom Field to Product under General
function create_extra_fee_field() {
$args = array(
'id' => 'park_fee',
'label' => __( 'Natl Park Entrance Fee', 'tranq-lsx-child' ),
'class' => 'tranq-custom-field',
'desc_tip' => true,
'description' => __( 'This sets the Fee that will be added to the car.', 'tranq-lsx-child' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'create_extra_fee_field' );
// Save Custom Field Data
function save_extra_fee_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['park_fee'] ) ? $_POST['park_fee'] : '';
$product->update_meta_data( 'park_fee', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'save_extra_fee_field' );
// Add Custom Field to Cart Totals
function woo_add_cart_fee() {
global $woocommerce;
foreach( WC()->cart->get_cart() as $cart_items ){
// Get the WC_Product object (instance)
$product = $cart_items['data'];
$product_id = $product->get_id(); // get the product ID
$custom_field_value = get_post_meta( $product->get_id(), 'park_fee', true );
$person = array_sum( $cart_items['booking']['_persons'] );
}
$additional_fee_name = "Natl Park Entrance Fee";
$extra_fee = $custom_field_value * $person;
$addedFee = false;
// first check to make sure it isn’t already there
foreach ( $woocommerce->cart->get_fees() as $_fee )
{
if ($_fee->id == sanitize_title($additional_fee_name) )
{
$_fee->amount = (float) esc_attr( $extra_fee );
}
}
if (!$addedFee)
{
$woocommerce->cart->add_fee( __($additional_fee_name, "woocommerce"),
$extra_fee, $additional_fee_taxable );
}
}
add_action( "woocommerce_before_calculate_totals", "woo_add_cart_fee" );
The one product is making use of that custom fee while the other product isn't its set to 0
But when both are added to the cart the fee just shows 0.
Is there any way to add both park fees together?
#Demonix, it is because the $custom_field_value is being overwritten with a '0' value, as the function loops through the attached products.
If you add in a statement to check if the park_fee is an actual number before replacing $custom_field_value
function woo_add_cart_fee() {
global $woocommerce;
$custom_field_value = 0;
foreach( WC()->cart->get_cart() as $cart_item ) {
// Get the WC_Product object (instance)
$product = $cart_item['data'];
$product_id = $product->get_id(); // get the product ID
$temp_value = get_post_meta( $product->get_id(), 'park_fee', true );
if ( false !== $temp_value && 0 !== $temp_value && '' !== $temp_value && '0' !== $temp_value ) {
$custom_field_value = $temp_value;
}
$person = array_sum( $cart_item['booking']['_persons'] );
}
$additional_fee_name = "Natl Park Entrance Fee";
$extra_fee = $custom_field_value * $person;
$addedFee = false;
// first check to make sure it isn’t already there
foreach ( $woocommerce->cart->get_fees() as $_fee ) {
if ($_fee->id == sanitize_title($additional_fee_name) ) {
$_fee->amount = (float) esc_attr( $extra_fee );
}
}
if (!$addedFee) {
$woocommerce->cart->add_fee( __($additional_fee_name, "woocommerce"),
$extra_fee, $additional_fee_taxable );
}
}
add_action( "woocommerce_before_calculate_totals", "woo_add_cart_fee" );
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.
Hi I'm experiencing some difficulties with the json_encode function in PHP.
I have an object with a hash (uniq ID) but it can have this format 5808e70581507 and because of the "e" surrounded with numbers I think json_encode is trying to set this fellow as an integer.
My object looks like this :
stdClass Object
(
[id] => 16
[title] => userinf2
[desc] => Travail →
[startoff] => 2016-10-20 05:00:00
[stop] => 2016-10-20 13:00:00
[status] => 1
[allDay] => 0
[code_mode] => M
[uid] => 31250
[gid] => 502935
[recurrence_id] =>
[recurrence_mode] =>
[recurrence_repeat_every] =>
[recurrence_repeat_day] =>
[recurrence_end_mode] =>
[recurrence_end_date] =>
[recurrence_end_number] =>
[multiple_timeschedule_id] => 5808e70581507
[start] => 2016-10-20 05:00:00
[end] => 2016-10-20 13:00:00
[color] => #7AE7BF
[className] => working uid_31250 code_mode_M gid_502935
)
Is there a way to make this working as it is ?
The code :
echo json_encode($events[6], JSON_NUMERIC_CHECK);
var_dump($events[6]->multiple_timeschedule_id); // string(13)
Assignment code :
function _oms_planning_planning_get()
{
try {
global $user;
$intervenants = _oms_planning_get_cab_intervenants();
$sql = 'SELECT * FROM planning_event WHERE 1=1 AND (';
$params_sql = array();
foreach ($intervenants as $key => $a_user) {
$sql .= ' uid =:uid' . $key . ' OR ';
$params_sql[':uid' . $key] = $a_user->uid;
}
$sql = substr($sql, 0, -3);
$sql .= ')';
$result = db_query($sql, $params_sql);
$db_events = $result->fetchAll();
$events = array_map(function ($db_event) use ($intervenants) {
$db_event->start = $db_event->startoff;
$db_event->end = $db_event->stop;
$db_event->color = (isset($db_event->gid) && intval($db_event->gid) > 0) ?
_oms_planning_planning_get_color_from_gid($db_event->gid) :
_oms_planning_planning_get_color_from_uid($intervenants, $db_event->uid);
$db_event->className = ($db_event->status == 1) ? 'working ' : 'idleness ';
$db_event->className .= 'uid_' . $db_event->uid . ' ';
$db_event->className .= 'code_mode_' . $db_event->code_mode . ' ';
$db_event->className .= 'gid_' . $db_event->gid;
return $db_event;
}, $db_events);
return $events;
} catch (Exception $e) {
print_r($e);
}
}
Mysql column type : multiple_timeschedule_id varchar(200) utf8_general_ci
I'm having trouble trying to send data from my handsontable table to my SQL database (phpMyAdmin). Data in this table is input by the user and when they click send it will insert all the data into an existing table in my database. Also, if they click load it will load all the all the rows from the database they are saving into. I'm currently working with the following scripts to try and send data to my database.
index.php (relevant code):
<!DOCTYPE html>
<html>
<head>
<title>SuburbMap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://code.jquery.com/jquery-1.12.0.js"></script>
<script src="http://docs.handsontable.com/0.16.0/bower_components/handsontable/dist/handsontable.full.js"></script>
<link type="text/css" rel="stylesheet" href="http://docs.handsontable.com/0.16.0/bower_components/handsontable/dist/handsontable.full.min.css">
<script src="http://docs.handsontable.com/0.16.0/bower_components/numeraljs/languages/de.js"></script>
<link rel="stylesheet" type="text/css" href="assets/admin-tools/admin-plugins/admin-panels/adminpanels.css">
<link rel="stylesheet" type="text/css" href="assets/admin-tools/admin-forms/css/admin-forms.css">
<link rel="shortcut icon" href="assets/img/favicon.ico">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<Style>
#loader {
z-index:99999;
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
body {
background-color: white;
margin: 20px;
}
h2 {
margin: 20px 0;
}
.handsontable-table {
overflow: scroll;
position: absolute;
top: 0px;
bottom: 54px;
width: 100%;
}
</style>
</head>
<body>
<div id="example1" class="dataTable"></div>
<p>
<button name="load" id="load">Load</button>
<button name="save" id="save">Save</button>
<label><input type="checkbox" name="autosave" id="autosave" checked="checked" autocomplete="off"> Autosave</label>
</p>
<script>
var
$container = $("#example1"),
$console = $("#exampleConsole"),
$parent = $container.parent(),
autosaveNotification;
$container.handsontable({
startRows: 8,
startCols: 3,
rowHeaders: true,
colHeaders: ['First Name', 'Last Name', 'Email', 'District/Suburb', 'Zip/Postcode', 'Income', 'No. Items', 'Item/Job Description'],
columns: [
{},
{},
{},
{},
{},
{},
{},
{}
],
minSpareCols: 0,
minSpareRows: 1,
contextMenu: true,
contextMenu: {
callback: function(key, options) {
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: ['row_above', 'row_below', 'remove_row', 'undo', 'redo', 'copy', 'paste'],
contextMenuCopyPaste: {
swfPath: '/managers/handsontable/dist/ZeroClipboard.swf'
}
},
afterChange: function (change, source) {
if (source === 'loadData') {
return; //don't save this change
}
if ($parent.find('input[name=autosave]').is(':checked')) {
clearTimeout(autosaveNotification);
$.ajax({
url: "/managers/save.php",
dataType: "json",
type: "POST",
data: {changes: change}, //contains changed cells' data
success: function () {
$console.text('Autosaved (' + change.length + ' cell' + (change.length > 1 ? 's' : '') + ')');
autosaveNotification = setTimeout(function () {
$console.text('Changes will be autosaved');
}, 1000);
}
});
}
}
});
var handsontable = $container.data('handsontable');
$parent.find('button[name=save]').click(function () {
$.ajax({
url: "/managers/save.php",
data: {"data": handsontable.getData()}, //returns all cells' data
dataType: 'json',
type: 'POST',
success: function (res) {
if (res.result === 'ok') {
$console.text('Data saved');
}
else {
$console.text('Save error');
}
},
error: function () {
$console.text('Save error');
}
});
});
$parent.find('button[name=reset]').click(function () {
$.ajax({
url: "/managers/reset.php",
success: function () {
$parent.find('button[name=load]').click();
},
error: function () {
$console.text('Data reset failed');
}
});
});
$parent.find('input[name=autosave]').click(function () {
if ($(this).is(':checked')) {
$console.text('Changes will be autosaved');
}
else {
$console.text('Changes will not be autosaved');
}
$parent.find('button[name=load]').click(function () {
$.ajax({
url: "/load.php",
dataType: 'json',
type: 'GET',
success: function (res) {
var data = [], row;
for (var i = 0, ilen = res.MultipleTerritories.length; i < ilen; i++) {
row = [];
row[0] = res.MultipleTerritories[i].fname;
row[1] = res.MultipleTerritories[i].lname;
row[2] = res.MultipleTerritories[i].email;
row[3] = res.MultipleTerritories[i].suburb;
row[4] = res.MultipleTerritories[i].postcode;
row[5] = res.MultipleTerritories[i].revenue;
row[6] = res.MultipleTerritories[i].noitems;
row[7] = res.MultipleTerritories[i].typeitems;
data[res.MultipleTerritories[i].id - 1] = row;
}
$console.text('Data loaded');
handsontable.loadData(data);
}
});
}).click(); //execute immediately
});
</script>
</body>
</html>
The following Scripts Are called from the script above:
functions.php script:
function &getConnection(){
$db = new PDO('mysql:host=localhost;dbname=suburbma;charset=utf8', 'suburbma***', '*****');
function closeConnection ($db){
$db = NULL;
}
//create the database if does not exist
function createMultipleTerritoriesTable($db){
$db->exec("CREATE TABLE IF NOT EXISTS MultipleTerritories (id INTEGER PRIMARY KEY, fname TEXT, lname TEXT, email TEXT, suburb TEXT, postcode INTEGER, revenue INTEGER, noitems INTEGER, typeitems TEXT)");
}
function resetMultipleTerritoriesTable($db){
dropMultipleTerritoriesTable($db);
createMultipleTerritoriesTable($db);
loadDefaultMultipleTerritories($db);
}
function dropMultipleTerritoriesTable($db){
$db->exec("DROP TABLE IF EXISTS multiple_suburbs");
}
function loadDefaultMultipleTerritories($db){
$query = $db->prepare('INSERT INTO multiple_suburbs(id, fname, lname, email, suburb, postcode, revenue, noitems, typeitems) VALUES(:id, :fname, :lname, :email, :suburb, :postcode, :revenue, :noitems, :typeitems)');
$data = array(
array(
'id' => 1,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 2,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 3,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 4,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 5,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 6,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 7,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 8,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
)
);
foreach($data as $index => $value){
$query->bindValue(':id', $value['id'], PDO::PARAM_INT);
$query->bindValue(':fname', $value['fname'], PDO::PARAM_STR);
$query->bindValue(':lname', $value['lname'], PDO::PARAM_STR);
$query->bindValue(':email', $value['email'], PDO::PARAM_STR);
$query->bindValue(':suburb', $value['suburb'], PDO::PARAM_STR);
$query->bindValue(':postcode', $value['postcode'], PDO::PARAM_INT);
$query->bindValue(':revenue', $value['revenue'], PDO::PARAM_INT);
$query->bindValue(':noitems', $value['noitems'], PDO::PARAM_INT);
$query->bindValue(':typeitems', $value['typeitems'], PDO::PARAM_STR);
$query->execute();
}
}
function &loadMultipleTerritories($db){
$select = $db->prepare('SELECT * FROM multiple_suburbs ORDER BY id ASC LIMIT 100');
$select->execute();
return $select;
}
function multiple_suburbsTableExists($db){
$result = $db->query("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='multiple_suburbs'");
$row = $result->fetch(PDO::FETCH_NUM);
return $row[0] > 0;
}
save.php:
<?php
require_once('functions.php');
try {
//open the database
$db = getConnection();
createMultipleTerritoriesTable($db);
$colMap = array(
0 => 'fname',
1 => 'lname',
2 => 'email',
3 => 'suburb',
4 => 'postocde',
5 => 'revenue',
6 => 'noitems',
7 => 'typeitems'
);
if (isset($_POST['changes']) && $_POST['changes']) {
foreach ($_POST['changes'] as $change) {
$rowId = $change[0] + 1;
$colId = $change[1];
$newVal = $change[8];
if (!isset($colMap[$colId])) {
echo "\n spadam";
continue;
}
$select = $db->prepare('SELECT id FROM multiple_suburbs WHERE id=? LIMIT 1');
$select->execute(array(
$rowId
));
if ($row = $select->fetch()) {
$query = $db->prepare('UPDATE multiple_suburbs SET `' . $colMap[$colId] . '` = :newVal WHERE id = :id');
} else {
$query = $db->prepare('INSERT INTO multiple_suburbs (id, `' . $colMap[$colId] . '`) VALUES(:id, :newVal)');
}
$query->bindValue(':id', $rowId, PDO::PARAM_INT);
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query->execute();
}
} elseif (isset($_POST['data']) && $_POST['data']) {
$select = $db->prepare('DELETE FROM multiple_suburbs');
$select->execute();
for ($r = 0, $rlen = count($_POST['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_POST['data'][$r]); $c < $clen; $c++) {
if (!isset($colMap[$c])) {
continue;
}
$newVal = $_POST['data'][$r][$c];
$select = $db->prepare('SELECT id FROM multiple_suburbs WHERE id=? LIMIT 1');
$select->execute(array(
$rowId
));
if ($row = $select->fetch()) {
$query = $db->prepare('UPDATE multiple_suburbs SET `' . $colMap[$c] . '` = :newVal WHERE id = :id');
} else {
$query = $db->prepare('INSERT INTO multiple_suburbs (id, `' . $colMap[$c] . '`) VALUES(:id, :newVal)');
}
$query->bindValue(':id', $rowId, PDO::PARAM_INT);
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query->execute();
}
}
}
$out = array(
'result' => 'ok'
);
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
reset.php:
<?php
require_once('functions.php');
try {
$db = getConnection();
resetMultipleTerritoriesTable($db);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
load.php:
<?php
/**
* This is an example code that shows how you can load Handsontable data from server using PHP with PDO (SQLite).
* This code is not intended to be maximally efficient nor safe. It is for demonstrational purposes only.
* Changes and more examples in different languages are welcome.
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://github.com/handsontable/handsontable/
*/
require_once('functions.php');
try {
//open the database
$db = getConnection();
if(!multiple_suburbsTableExists($db)){
resetMultipleTerritoriesTable($db);
}
//select all data from the table
$result = loadMultipleTerritories($db);
$out = array(
'multiple_suburbs' => $result->fetchAll(PDO::FETCH_ASSOC)
);
echo json_encode($out);
// close the database connection
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
I tired to fix this line:
if ( $_GET['paged'] ) && ! empty( $_GET['paged'] ) ) {
on my functions.php , but with no succes ! i'm really stuck! i get wordpress theme, syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in functions.php on line 118
<?php
/**
*
* # Release: Me
*
**/
function get_category_id($cat_name) {
$term = get_term_by( 'name', $cat_name, 'category' );
return $term->term_id;
}
function kisabaslik($char) {
$title = get_the_title( $post->ID );
$title = mb_substr( $title, 0, $char, 'UTF-8' );
echo $title;
}
function kisaicerik($kisacik) {
$icerik = get_the_content( $post->ID );
$icerik = mb_substr( $icerik, 0, $kisacik, 'UTF-8' );
str_replace( '</strong>', '', $icerik );
$icerik = str_replace( '<strong>', '', $icerik );
echo strip_tags( $icerik );
}
function the_breadcrumb() {
global $post;
if (!is_home( )) {
echo '<a href=\'uploadify.php';
echo get_option( 'home' );
echo '\'> » ';
echo get_option( 'echo_kisasiteadresi' );
echo '</a>';
if (( is_category( ) || is_single( ) )) {
echo ' » ';
$cats = get_the_category( $post->ID );
foreach ($cats as $cat) {
$cat = $cat[0];
$category_id = get_cat_id( $cat->cat_name );
$category_link = get_category_link( $category_id );
echo '<a href="' . esc_url($category_link ) . '" title="' . $cat->cat_name . '">';
echo $cat->cat_name;
echo '</a>';
echo ' » ';
}
if (is_single( )) {
echo '<a href="';
the_permalink( );
echo '">';
the_title( );
echo '</a>';
return null;
}
}
else {
if (is_page( )) {
if ($post->post_parent) {
$anc = get_post_ancestors( $post->ID );
$anc_link = get_page_link( $post->post_parent );
foreach ($cats as $cat) {
$ancestors = get_ancestors(
$output = '<a href="'. $anc_link . '>' . get_the_title( $ancestor ) . "'</a>';
}
echo $output;
the_title( );
return null;
}
echo ' » ';
echo the_title( );
return null;
}
}
}
else {
if (is_tag( )) {
single_tag_title( );
return null;
}
if (is_day( )) {
echo 'Archive: ';
the_time( 'F jS, Y' );
echo '</li>';
return null;
}
if (is_month( )) {
echo 'Archive: ';
the_time( 'F, Y' );
echo '</li>';
return null;
}
if (is_year( )) {
echo 'Archive: ';
the_time( 'Y' );
echo '</li>';
return null;
}
if (is_author( )) {
echo 'Author\'s archive: ';
echo '</li>';
return null;
}
if ( $_GET['paged'] ) && ! empty( $_GET['paged'] ) ) {
echo 'Blogarchive: ';
echo '</li>';
return null;
}
if (is_search( )) {
echo 'Search results: ';
}
}
}
function searchfilter($query) {
if ($query->is_search) {
$query->set( 'post_type', 'post' );
}
return $query;
}
function toplamoynanma() {
$queryvvv = mysql_query( 'SELECT sum(meta_value) FROM wp_postmeta where meta_key=\'views\'' );
$rowvvvv = mysql_fetch_array( $queryvvv );
echo number_format( $rowvvvv[0] );
}
function oyhesapla($id) {
$begen = error_reporting( 0 );
$begenme = get_post_meta( $id, 'begenme', true );
$toplamoy3 = $begen + $begenme;
$toplamoy = $begen - $begenme;
$begenmeoy = 1 * $begenme;
$begenoy = 5 * $begen;
$toplamoy2 = $begenoy + $begenmeoy;
$fark = $toplamoy * 100 / $toplamoy2;
$islem = $fark / 10;
round( $islem, 2 );
$sonuc = get_post_meta( $id, 'begen', true );
$sonuc1 = explode( '.', $sonuc );
$sonuc2 = ceil( $sonuc1[1] / 10 );
if (!$sonuc2) {
$sonuc2 = $sonuc / 10;
}
if (10 < $sonuc2) {
$sonuc2 = 40;
}
if ($sonuc2 < 1) {
$sonuc2 = 31;
}
echo $toplamoyS;
echo '<b>' . $sonuc2 . ' / 10 </b><span>( ' . $toplamoy3 . ' members of the game.)</span>';
}
function favkon($id) {
$cookiefav = 'favoricook[' . $id . ']';
if ($_SESSION[$cookiefav]) {
echo '<a class="favorileA">Favorite Games.</a>
';
return null;
}
echo '<a class="favorile" onclick="favoriEkle(';
echo $id;
echo ');">Add Favorite</a>
';
}
function echoyazibegenme($postid) {
global $tema;
echo '
<div style=" margin-top:10px; ';
if ($d == 2) {
echo 'float:right;';
}
echo '">
<div class="oysonuc"></div>
';
$cookieoysv = 'obegenbegenme' . $postid;
echo '
<div class="sYas">
<a id="begen" onclick="oyver(';
echo $postid;
echo ',1);" class="begenButon" title="BeÄŸen"></a><div class="begenButonS">';
echo '<s';
echo 'pan>';
if (!get_post_meta( $postid, 'begen', true )) {
echo '0';
}
else {
echo get_post_meta( $postid, 'begen', true );
}
echo '</span></div>
<a id="begenme" style="margin-top:0" onclick="oyver(';
echo $postid;
echo ',2);" class="begenmeButon" title="BeÄŸenme"></a><div class="begenmeButonS">';
echo '<s';
echo 'pan>';
if (!get_post_meta( $postid, 'begenme', true )) {
echo '0';
}
else {
echo get_post_meta( $postid, 'begenme', true );
}
echo '</span></div>
</div>
';
echo '<s';
echo 'cript>
function oyver(id,is){
if(is==1){
var begenic = $(".begenButonS span").text();
begenic++;
}
if(is==2){
var begenmeic = $(".begenmeButonS span").text();
begenmeic++;
}
$.ajax( {
url: "';
echo $tema;
echo 'oyislem.php?islem="+is+"&postID="+id,
success: function(cevap) {
if(cevap==0){
$(".oysonuc").fadeIn(500);
$(".oysonuc").html("<div class=\'uyar\'>The procedure before you did it.</div>").delay(3000);
$(".oysonuc").fadeOut(500);
}
if(is==1 && cevap==1){
$(".begenButonS span").html(begenic);
}
if(is==2 && cevap==1){
$(".begenmeButonS span").html';
echo '(begenmeic);
}
}
});
}
</script>
</div>
';
}
function redirect_after_comment($location) {
return $_SERVER['HTTP_REFERER'] . '#yorum';
}
function kategori_post_say($id) {
$count = 31;
$taxonomy = 'category';
$args = array( 'child_of' => $id );
$tax_terms = get_terms( $taxonomy, $args );
foreach ($tax_terms as ) {
$tax_term = [0];
$tax_term->count;
$count += ;
}
return $count;
}
add_action( 'wp_head' );
$botresim = $tema = get_bloginfo( 'template_url' ) . '/';
get_option( 'echo_botswf' );
$botswf = get_option( 'echo_botresim' );
add_theme_support( 'post-thumbnails' );
add_image_size( 'yeniOyunRes', 147, 119, true );
add_image_size( 'onerilenOyunlar', 330, 205, true );
add_image_size( 'mansetOyun', 330, 100, true );
require_once( TEMPLATEPATH . '/admin/admin-functions.php' );
require_once( TEMPLATEPATH . '/admin/admin-interface.php' );
require_once( TEMPLATEPATH . '/admin/theme-settings.php' );
register_nav_menu( 'kategori-menu', 'Kategori' );
add_filter( 'pre_get_posts', 'SearchFilter' );
$botresim = register_nav_menu( 'sayfalar', 'Alt Kısımdaki Sayfalar Bölümü' );
get_option( 'echo_botswf' );
$botswf = get_option( 'echo_botresim' );
get_category_id( get_option( 'echo_oyunvideo' ) );
$oyunvideo = add_filter( 'comment_post_redirect', 'redirect_after_comment' );
?>
The issue with your php is that you are closing the if statement then adding extravariables to nothing. It should look like this:
if ( $_GET['paged'] && ! empty( $_GET['paged'] ) ) {