Woocommerce Subscriptions update next payment date from functions.php - function

I would like to change the next payment date of active subscriptions after the Initial (first) Subscription payment is completed after the trial period.
<?php global $woocommerce;
$all_meta_for_user = get_user_meta( 53 );
$order = new WC_Order(4843);
$order_id=4846;//PUT YOUR ORDER ID HERE
$subscription = wcs_get_subscription( 4846 );
add_action('woocommerce_subscription_payment_complete', 'nextpaymentdatechange', 10, 1);
function nextpaymentdatechange($order_id){
if (WC_Subscriptions_Order::order_contains_subscription($order_id)) {
$nextdate = get_post_meta( $order_id, '_schedule_next_payment', true );
$threedays_ago = date('Y-m-d H:i:s', strtotime('-15 days', strtotime($nextdate)));
update_post_meta($order_id , '_schedule_next_payment', $threedays_ago);
}
} ?>

I got a solution for the subscription-related question which posted. It may help others.
function pro_subscription($subscription){
$sid = $subscription->id;
$uid = $subscription->customer_user;
$subscription = wcs_get_subscription( $sid );
$items = $subscription->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$order_id = $subscription->get_parent_id();
}
$subscription_key = WC_Subscriptions_Manager::get_subscription_key( $order_id, $product_id);
$td = new DateTime($subscription->get_date( 'trial_end_date' ));
$try_date = $td->format('Y-m-d');
$sd = new DateTime($subscription->get_date( 'next_payment_date' ));
$pay_date = $sd->format('Y-m-d');
$sdt = new DateTime($subscription->get_date( 'start_date' ));
$sst = $sd->format('Y-m-d H:i:s');
$tst = $td->format('Y-m-d H:i:s');
$date1=date_create($tst);
$date2=date_create($sst);
$diff=date_diff($date1,$date2);
$df = 30 - $diff->format("%a");
$next_pay = date('Y-m-d H:i:s', strtotime($ts. ' + ' . $df . ' days'));
if($try_date == $pay_date){
WC_Subscriptions_Manager::set_next_payment_date( $subscription_key, $uid, $next_pay );
}
}

Related

Subtracting fields from two different tables and updating the value during update in Laravel

I have two different tables, table_employee and table_leave. table_employee contains fields such as emp_id, paid_vacation(In Hours), used_vacation(in Hours), while table_leave contains id, hours_spent(in Hours). please how can i deduct the hours_spent in the table_leave from used from the paid_vacation in the table_employee and then update the used_vacation in table_employee with the new value
for instance. paid_vacation =150 hours, used_vacation = 0, hours_spent= 8 hours, with this, this used_vacation should be updated to 150 -8 hours = 142 hours left. I want deduct and update back in the table.
private function saveEmployeeLeave(Request $request, $id=null){
if($id != NULL){
$employeeId = DB::table('as_tbl_employee_master')
->where('employee_id', $request->employee_id)
->get();
}
$employee_id = $request->employee_id;
$paid_vacation = $request->paid_vacation;
$used_vacation = $request->used_vacation;
$empData = new AsEmployee();
if($id !== null) {
$empData = AsEmployee::find($id);
if($empData == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empData->employee_id = $employee_id;
$empData->paid_vacation = $paid_vacation;
$empData->used_vacation = $used_vacation;
$empData->save();
// $emp_id = $request->emp_id;
$emp_id = $request->emp_id;
$dept = $request->department_id;
$english_name = $request->english_name;
$department = $request->department;
$selectedLeaveType = $request->selectedLeaveType;
$application_time = date('Y-m-d H:i:s');
$date_from = $request->date_from;
$date_to = $request->date_to;
$comment = $request->comment;
$contact = $request->contact;
$hours = $request->hours;
$approval_emp_id = $request->reports_to;
$manager = $request->manager;
$status = $request->status;
$empInfo = new AsEmployeeLeave();
if($id !== null) {
$empInfo = AsEmployeeLeave::find($id);
if($empInfo == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empInfo->emp_id = $emp_id;
$empInfo->department_id = $dept;
$empInfo->application_time = $application_time;
$empInfo->type = $selectedLeaveType;
$empInfo->date_from = $date_from;
$empInfo->date_to = $date_to;
$empInfo->comment = $comment;
$empInfo->requester_emp_id = $emp_id;
$empInfo->requester_sign = $english_name;
$empInfo->approval_emp_id = $approval_emp_id;
$empInfo->approval_sign = $manager;
$empInfo->contact = $contact;
$empInfo->hours = $hours;
$empInfo->status = $status;
$empInfo->save();
return $empData;
}
I called it inside this function
public function addEmpLeave(Request $request){
$responseData = $this->saveEmployeeLeave($request);
return ($responseData instanceof JsonResponse) ? $responseData : $this->sendResponse($responseData);
}
Try this :
private function saveEmployeeLeave(Request $request, $id=null){
if($id != NULL){
$employeeId = DB::table('as_tbl_employee_master')
->where('employee_id', $request->employee_id)
->get();
}
$employee_id = $request->employee_id;
$paid_vacation = $request->paid_vacation;
$used_vacation = $request->used_vacation;
$empData = new AsEmployee();
if($id !== null) {
$empData = AsEmployee::find($id);
if($empData == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empData->employee_id = $employee_id;
$empData->paid_vacation = $paid_vacation;
$empData->used_vacation = $used_vacation;
$empData->save();
// $emp_id = $request->emp_id;
$emp_id = $request->emp_id;
$dept = $request->department_id;
$english_name = $request->english_name;
$department = $request->department;
$selectedLeaveType = $request->selectedLeaveType;
$application_time = date('Y-m-d H:i:s');
$date_from = $request->date_from;
$date_to = $request->date_to;
$comment = $request->comment;
$contact = $request->contact;
$hours = $request->hours;
$approval_emp_id = $request->reports_to;
$manager = $request->manager;
$status = $request->status;
$empInfo = new AsEmployeeLeave();
if($id !== null) {
$empInfo = AsEmployeeLeave::find($id);
if($empInfo == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empInfo->emp_id = $emp_id;
$empInfo->department_id = $dept;
$empInfo->application_time = $application_time;
$empInfo->type = $selectedLeaveType;
$empInfo->date_from = $date_from;
$empInfo->date_to = $date_to;
$empInfo->comment = $comment;
$empInfo->requester_emp_id = $emp_id;
$empInfo->requester_sign = $english_name;
$empInfo->approval_emp_id = $approval_emp_id;
$empInfo->approval_sign = $manager;
$empInfo->contact = $contact;
$empInfo->hours = $hours;
$empInfo->status = $status;
$empInfo->save();
$empData = AsEmployee::find($empData->id);
$empData->used_vacation = (int)$paid_vacation - (int)$hours;
$empData->save();
return $empData;
}

How to update table in redbeanphp

Here is my function Insert.
What should i write after findOne to UPDATE the table. If field name exist update all other fields.
function insert_data_score($name, $clickcountscore, $levelofitems, $bonuscounter, $date, $timeofcasinobutton, $timeofcasinovideo){
$repeatChecker = R:: findOne('clicker', 'name = ?', array ($name));
if (isset($repeatChecker))
// ????????
return " User $name exist";
$scoreboard = R::xdispense( 'clicker' );
$scoreboard->name = $name;
$scoreboard->clickcountscore = $clickcountscore;
$scoreboard->levelofitems = $levelofitems;
$scoreboard->bonuscounter = $bonuscounter;
$scoreboard->date = $date;
$scoreboard->timeofcasinobutton = $timeofcasinobutton;
R::store($scoreboard);
return "User: $name, created";
$repeatChecker->clickcountscore = $clickcountscore;
$repeatChecker->levelofitems = $levelofitems;
$repeatChecker->bonuscounter = $bonuscounter;
$repeatChecker->date = $date;
$repeatChecker->timeofcasinobutton = $timeofcasinobutton;
$repeatChecker->timeofcasinovideo = $timeofcasinovideo;
R::store($repeatChecker);
return " User $name Updated";
all wokrs if add this code after "if"

Import CSV in Mysql does not work

I like to write a csv import / update to my Mysql database, but it isnt working. I get no error messages.
Can anybody help me to find the error or whats wrong with my script please.
// set local variables
$connect = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
$handle = fopen("imptest.csv", "r");
// connect to mysql and select database or exit
mysql_select_db("shoptest1", $connect);
while($data = fgetcsv($handle, 30000, ';')) //Jede Zeile durchgehen
{
$Product_ID=$data[0];
$field=$data[1];
$query = 'SELECT Product_ID FROM testprod';
if (!$result = mysql_query($query)) {
continue;
} if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// entry exists update
$query = "UPDATE ps_product_lang SET custom_field ='$field' WHERE id_product = '$Product_ID'";
mysql_query($query);
if (mysql_affected_rows() <= 0) {
echo "kein update";
// no rows where affected by update query
}
} else {
echo "kein eintrag";
// entry doesn't exist continue or insert...
}
mysql_free_result($result);
}
fclose($handle);
mysql_close($connect);
?>
The queries you are performing:
SELECT Product_ID FROM testprod
UPDATE nl_product_lang SET custom_field = ? WHERE Product_ID = ?
are suitable to detect whether a product exists and then either UPDATE or INSERT. For only an UPDATE, the SELECT doesn't matter, as there won't be an entry WHERE Product_ID NOT IN (SELECT Product_ID FROM testprod) - if you have a foreign key.
Here's an example of how to do this using PDO.
list( $SQLDSN, $SQLUSER, $SQLPASS ) = [ 'mysql:dbname=shoptest1', 'root', '' ];
$db = new PDO( $SQLDSN, $SQLUSER, $SQLPASS, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
] );
$ids = $db->query( "SELECT Product_ID from testprod" )->fetchAll( \PDO::FETCH_COLUMN, 0 );
while ( list( $Product_ID, $field ) = fgetcsv(...) )
if ( in_array( $Product_ID, $ids ) )
query( $db, "UPDATE ps_product_lang SET custom_field = ? WHERE Product_ID = ?",
[ $field, $Product_ID ]
);
else
trigger_warning( "unknown product $Product_ID" );
function query( $db, $sql, $args = null ) {
$sth = $db->prepare( $sql );
$sth->execute( $sql );
return $sth;
}

Looking for a cleaner way to run a query that has to check for multiple "AND" conditions

I'm running a query against a database and have to check for multiple conditions to be true. The code I have pulls the data I want, but if I had to check many more columns, it could get out of control very quickly. I don't want a query that where I have to write out a dozen or so "AND" conditions. I'm learning some MySQL as I go and any help would be appreciated.
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Set up and run my Query
$sql = "SELECT Project, Client, DateReceived, LastName, FinalReviewDate FROM Projects
WHERE FinalReviewDate IS NOT NULL
AND DateDelivered IS NULL
AND DateAccepted IS NULL
ORDER BY DateAccepted DESC";
$result = $conn->query($sql);
//Display results
if ($result->num_rows > 0) {
echo "<table><tr><th>Client</th><th>Project</th><th>Point of Contact</th><th>Date Project Received</th><th>Final Review Date</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row ["Project"]. "</td><td> " . $row["LastName"]. "</td><td> " . $row ["DateReceived"]. "</td><td> " . $row["FinalReviewDate"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
You can use an array for your and conditions. But in general you have to be careful if you are going to have prepared statements and bind values. Also, you can create your WHERE clause dynamically in a similar way like the following:
EDIT:
$where = array(
array(
'column'=>'FinalReviewDate',
'operator'=>'AND',
'condition'=>'IS NOT NULL',
'value'=>'',
),
array(
'column'=>'DateDelivered',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'DateAccepted',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'other_column',
'operator'=>'OR',
'condition'=>'>=',
'value'=>5,
),
);
$temp = array();
foreach($where as $key => $value) {
if ($value['value'] == '') {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'];
} else {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'].' '.$value['value'];
}
}
$where_sql = '1 = 1 '.implode(' ', $temp);
echo $where_sql;
Result:
1 = 1 AND FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL OR other_column >= 5
OLD ANSWER
$ands = array(
array(
'column'=>'FinalReviewDate',
'condition'=>'IS NOT NULL'
),
array(
'column'=>'DateDelivered',
'condition'=>'IS NULL'
),
array(
'column'=>'DateAccepted',
'condition'=>'IS NULL'
),
);
$temp = array();
foreach($ands as $key => $value) {
$temp[] = $value['column'].' '.$value['condition'];
}
$and_sql = implode(' AND ', $temp);
echo $and_sql;
Result:
FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL

A duplicate key is inserted instead of updated in a SQL INSERT / UPDATE query

I have the below function in Wordpress.
However, the meta key product_price is duplicated each time a post is updated.
Like this image
Is there any way to prevent this?
function do_my_stuff($post_ID) {
global $post,$wpdb;
$tablename="wp_cart66_products";
if($post->post_type == "post" && strlen( get_post_meta($post_ID, 'price', true))>0 )
{
$id = $wpdb->get_var("SELECT id FROM ".$tablename." WHERE id=".$post_ID);
$cny = get_post_meta($post->ID, 'price', true);
/*Shipping rate */
if( $cny < 50 )
$shipping = 14.97;
else if( $cny >= 50 && $cny < 200 )
$shipping = 22.59;
else if( $cny >= 200 && $cny < 250 )
$shipping = 24.59;
else if( $cny >= 250 && $cny < 300 )
$shipping = 26.60;
else if( $cny >= 300 )
$shipping = 29.27;
/*Exchange rate CNY to EURO */
$cny_to_euro = 0.124;
$euro = $cny * $cny_to_euro ;
$price = $euro + $shipping;
$price = number_format($price,2);
$data=array(
'id'=>$post_ID,
'item_number'=>get_post_meta($post->ID, 'scode', true),
'name'=>$post->post_title,
'price'=>$price,
'options_1'=>get_post_meta($post->ID, 'variations', true),
'shipped'=>'1',
);
$where = array("id" => $post_ID);
// Possible format values: %s as string; %d as decimal number; and %f as float.
$format=array( '%d', '%s', '%s', '%s', '%s', '%d');
$where_format = array( '%d' );
if($id>0){
// update
$wpdb->update( $tablename,$data, $where, $format, $where_format);
}else{
// insert
$wpdb->insert( $tablename,$data,$format);
}
AddMetaPrice ( $post_ID ) ;
}
return $post_ID;
}
function AddMetaPrice ( $post_ID )
{
// init
global $post,$wpdb;
// We add the wordpress post ID and price to a meta tag
$metaKey = "product_price" ;
$tableName = "wp_cart66_products" ;
$metaQuery = "SELECT price FROM $tableName WHERE id='$post_ID'" ;
$metaValue = $wpdb->get_var( $metaQuery ) ;
$tableName = "wp_postmeta" ;
// Do we have this post already?
if ( $id > 0 )
{
// this already exists. we only need to update
// $metaQuery = "UPDATE $tableName SET meta_value='$metaValue' WHERE meta_key='$metaKey' AND post_id='$id'" ; // we use wordpress's method instead
$data = array ( "meta_value" => $metaValue ) ;
$where = array ( "meta_key" => $metaKey, "post_id" => $post_ID ) ;
$wpdb->update( $tableName, $data, $where ) ;
}
else
{
// this is not created, we need to create it now (insert)
// $metaQuery = "INSERT INTO $tableName (post_id, meta_key, meta_value) VALUES ('$id', '$metaKey', '$metaValue')" ; // we use wordpress's method instead
$data = array ( "post_id" => $post_ID, "meta_key" => $metaKey, "meta_value" => $metaValue ) ;
$wpdb->insert( $tableName, $data ) ;
}
}
add_action('publish_post', 'do_my_stuff');
I've read here that a ON DUPLICATE KEY statement exists. But i'm not sure if it can be implemented in the above code.
Try replacing that piece of code:
if ( $metaValue !== NULL )
{
update_post_meta($post_ID, $metaKey, $metaValue); // use built-in function instead
}
where it was:
// Do we have this post already?
if ( $id > 0 )
{
// this already exists. we only need to update
// $metaQuery = "UPDATE $tableName SET meta_value='$metaValue' WHERE meta_key='$metaKey' AND post_id='$id'" ; // we use wordpress's method instead
$data = array ( "meta_value" => $metaValue ) ;
$where = array ( "meta_key" => $metaKey, "post_id" => $post_ID ) ;
$wpdb->update( $tableName, $data, $where ) ;
}