Associative array corresponding to column name in a table - php

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Post.php';
$database = new Database();
$db = $database->connect();
$post = new Post($db);
$result = $post->read();
$num = $result->rowCount();
if ($num > 0) {
$posts_arr = array();
$posts_arr['data'] = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
extract($row);
$post_item = array(
'id' => $id,
'title' => $title,
'body' => html_entity_decode($body),
'author' => $author,
'category_id' => $category_id,
'category_name' => $category_name
);
array_push($posts_arr['data'], $post_item);
echo json_encode($posts_arr);
}
} else {
echo json_encode(
array('message' => 'No Posts Found')
);
}
My problem :
I try to change $title to $the_title, it generates error, but when I change the column name in the table to 'the_title', it works!
My confusion is that since anything start with '$' sign is a variable, and it can be any name actually, but in this particular situation, why the name of the variable needs to be same as the name of the table's column.
$post_item = array(
'id' => $id,
'title' => $title,
'body' => html_entity_decode($body),
'author' => $author,
'category_id' => $category_id,
'category_name' => $category_name
);

Related

Woocommerce in stock Notifier Api

i am using in stock notifier plugin https://wordpress.org/plugins/back-in-stock-notifier-for-woocommerce/
in this plugin rest api or plugin of rest api not given
i am making custom rest api plugin and insert data in a table but email not coming during subscription of email id
and during in stock of product.
my custom code for instock api
<?php
/**
* Plugin Name: Very First Plugin
* Plugin URI: https://www.yourwebsiteurl.com/
* Description: This is the very first plugin I ever created.
* Version: 1.0
* Author: Your Name Here
* Author URI: http://yourwebsiteurl.com/
**/
/**
* Grab latest post title by an author!
*
* #param array $data Options for the function.
* #return string|null Post title for the latest,
 * or null if none.
*/
/*
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/authorsss/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
*/
function my_awesome_func( $data ) {
global $wpdb;
if($data['cwginstock_user_id']==''){
$students_arr = array(
"responseCode" => 400,
"responseMessage" => "Please enter user id.",);
echo json_encode($students_arr);
}elseif($data['cwginstock_subscriber_email'] == ''){
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter email id.",);
echo json_encode($students_arr);
}elseif($data['cwginstock_pid'] == ''){
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter product id.",);
echo json_encode($students_arr);
}else{
$tablename2 = $wpdb->prefix . "posts";
//himanshu-swamiitechs-co-in__trashed
$ok = str_replace(".","",$data['cwginstock_subscriber_email']);
$post_name = str_replace("#","-",$ok);
$res = $wpdb->insert(
$tablename2,
array(
'post_author' => $data['cwginstock_user_id'],
'post_content' => "",
'post_title' => $data['cwginstock_subscriber_email'],
'post_excerpt' => "",
'post_name'=>$post_name,
'post_status' =>'cwg_subscribed',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => "",
'to_ping' => "",
'pinged' => "",
'post_content_filtered' =>'',
'post_parent' =>'',
//'guid' => 'http://localhost/ecommerces4/cwginstocknotifier/himanshu-swamiitechs-co-in/',
'guid' => 'http://localhost/ecommerces4/cwginstocknotifier/'.$post_name.'/',
"menu_order"=> 0,
"post_type"=> "cwginstocknotifier",
"post_mime_type" =>"",
"comment_count"=> 0,
"post_date"=>Date('Y-m-d H:i:s'),
"post_date_gmt"=>Date('Y-m-d H:i:s'),
"post_modified_gmt" =>Date('Y-m-d H:i:s'),
"post_modified"=>Date('Y-m-d H:i:s')
)
);
$lastid = $wpdb->insert_id;
$data1 = array(
'cwginstock_variation_id',
'cwginstock_subscriber_email',
'cwginstock_user_id',
'cwginstock_language',
'cwginstock_pid'
);
$data3 = array(0, $data['cwginstock_subscriber_email'],
$data['cwginstock_user_id'], "en_US",$data['cwginstock_pid']
);
$tablename = $wpdb->prefix . "postmeta";
foreach ($data1 as $key => $value) {
$res = $wpdb->insert(
$tablename,
array(
'post_id' => $lastid,
'meta_key' => $value,
'meta_value' => $data3[$key]
)
);
}
if($res){
echo 'inserted';
}else{
echo 'not inserted';
}
return $wpdb;
}
}
add_action( 'rest_api_init', function () {
$namespace = 'myplugin/v1';
$endpoint = '/authorsss/';
register_rest_route( $namespace, $endpoint, array(
'methods' => 'GET',
'callback' => 'my_awesome_func'
) );
} );
i want to proper insert data in database, email alert is not coming and
in admin side in plugin product name not showing even i am sending product id
I wanted to do the same thing. I used your code as a base to start but changed some small things and it works now.
//himanshu-swamiitechs-co-in__trashed
$ok = str_replace(".","-",$data['cwginstock_subscriber_email']);
$post_name = str_replace("#","",$ok);
the str_replace needed to be different. replace . by - and remove #
$data1 = array(
'cwginstock_product_id' ,
'cwginstock_variation_id',
'cwginstock_subscriber_email',
'cwginstock_user_id',
'cwginstock_language',
'cwginstock_pid' ,
);
Secondly this is the right order and variables
Underneath you can see the whole code I used
function back_in_stock_email ( $data) {
// Get request params
global $wpdb;
if ($data['cwginstock_user_id']=='') {
$students_arr = array(
"responseCode" => 400,
"responseMessage" => "Please enter user id.",);
echo json_encode($students_arr);
} elseif ($data['cwginstock_subscriber_email'] == '') {
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter email id.",);
echo json_encode($students_arr);
} elseif($data['cwginstock_pid'] == '') {
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter product id.",);
echo json_encode($students_arr);
} else {
$tablename2 = $wpdb->prefix . "posts";
//himanshu-swamiitechs-co-in__trashed
$ok = str_replace(".","-",$data['cwginstock_subscriber_email']);
$post_name = str_replace("#","",$ok);
$res = $wpdb->insert(
$tablename2,
array(
'post_author' => "0",
'post_content' => "",
'post_title' => $data['cwginstock_subscriber_email'],
'post_excerpt' => "",
'post_name'=>$post_name,
'post_status' =>'cwg_subscribed',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => "",
'to_ping' => "",
'pinged' => "",
'post_content_filtered' =>'',
'post_parent' =>'',
'guid' => '<YOUR BASE URL>/cwgstocknotifier/'.$post_name.'/',
"menu_order"=> "0",
"post_type"=> "cwginstocknotifier",
"post_mime_type" =>"",
"comment_count"=> "0",
"post_date"=>Date('Y-m-d H:i:s'),
"post_date_gmt"=>Date('Y-m-d H:i:s'),
"post_modified_gmt" =>Date('Y-m-d H:i:s'),
"post_modified"=>Date('Y-m-d H:i:s')
)
);
$lastid = $wpdb->insert_id;
echo $lastid;
$data1 = array(
'cwginstock_product_id' ,
'cwginstock_variation_id',
'cwginstock_subscriber_email',
'cwginstock_user_id',
'cwginstock_language',
'cwginstock_pid' ,
);
$data3 = array($data['cwginstock_pid'], $data['cwginstock_variation_id'],
$data['cwginstock_subscriber_email'], "0","en_US",$data['cwginstock_pid']);
$tablename = $wpdb->prefix . "postmeta";
foreach ($data1 as $key => $value) {
$res = $wpdb->insert(
$tablename,
array(
'post_id' => $lastid,
'meta_key' => $value,
'meta_value' => $data3[$key]
)
);
}
if ($res) {
echo 'inserted';
} else {
echo 'not inserted';
}
return $wpdb;
}
}

Wordpress Custom database table with DataTable server side processing

I have followed this toturial and have managed to create a shortcode that shows the datatable with filter option. This table works with the native post type of wordpress.
I need the same datatable but it should get the data from a custom database table i have added wp_lubuvna_subscribers
Custom Table:
So i need to change following function to get data from the above mentioned custom table instead custom post type
function datatables_server_side_callback_subscriber_db() {
header("Content-Type: application/json");
$request= $_GET;
$columns = array(
0 => 'post_title',
3 => LUBUVNA_PREFIX.'email',
1 => LUBUVNA_PREFIX.'first_name',
2 => LUBUVNA_PREFIX.'last_name',
4 => LUBUVNA_PREFIX.'phone'
);
$args = array(
'post_type' => 'lubuvna_subscriber',
'post_status' => 'publish',
'posts_per_page' => $request['length'],
'offset' => $request['start'],
'order' => $request['order'][0]['dir'],
);
if ($request['order'][0]['column'] == 0) {
$args['orderby'] = $columns[$request['order'][0]['column']];
} elseif ($request['order'][0]['column'] == 1 || $request['order'][0]['column'] == 2) {
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = $columns[$request['order'][0]['column']];
}
//$request['search']['value'] <= Value from search
if( !empty($request['search']['value']) ) { // When datatables search is used
$args['meta_query'] = array(
'relation' => 'OR',
array(
'key' => 'd_title',
'value' => sanitize_text_field($request['search']['value']),
'compare' => 'LIKE'
),
array(
'key' => LUBUVNA_PREFIX.'email',
'value' => sanitize_text_field($request['search']['value']),
'compare' => 'LIKE'
),
array(
'key' => LUBUVNA_PREFIX.'first_name',
'value' => sanitize_text_field($request['search']['value']),
'compare' => 'LIKE'
),
array(
'key' => LUBUVNA_PREFIX.'last_name',
'value' => sanitize_text_field($request['search']['value']),
'compare' => 'LIKE'
),
array(
'key' => LUBUVNA_PREFIX.'phone',
'value' => sanitize_text_field($request['search']['value']),
'compare' => 'LIKE'
),
);
}
$subscriber_query = new WP_Query($args);
$totalData = $subscriber_query->found_posts;
if ( $subscriber_query->have_posts() ) {
while ( $subscriber_query->have_posts() ) {
$subscriber_query->the_post();
$nestedData = array();
$nestedData[] = get_field(LUBUVNA_PREFIX.'first_name'). '&nbsp'. get_field(LUBUVNA_PREFIX.'last_name');
$nestedData[] = "<a data-val='".get_post_field( 'post_name', get_post() )."' href='".get_permalink()."' data-posttype='".get_post_type( get_the_ID() )."' class='generallink'>" . get_field(LUBUVNA_PREFIX.'email') . "</a>";
$nestedData[] = get_field(LUBUVNA_PREFIX.'first_name');
$nestedData[] = get_field(LUBUVNA_PREFIX.'last_name');
$nestedData[] = get_field(LUBUVNA_PREFIX.'phone');
$data[] = $nestedData;
}
wp_reset_query();
$json_data = array(
"draw" => intval($request['draw']),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalData),
"data" => $data
);
echo json_encode($json_data);
} else {
$json_data = array(
"data" => array()
);
echo json_encode($json_data);
}
wp_die();
}
So i will post this here, in case someone else is looking for the same solution. I had to add global $wpdband get the data from my custom database table. it works perfectly with paging / sorting / Search.
function datatables_server_side_callback_subscriber_db() {
header("Content-Type: application/json");
global $wpdb;
// Table name
$table_name = $wpdb->prefix . "lubuvna_subscribers";
// Request
$request= $_GET;
// Columns
$columns = array(
0 => 'ID',
1 => 'first_name',
2 => 'last_name',
3 => 'email',
4 => 'phone'
);
// Datatable Filters
$column = $columns[$request['order'][0]['column']];
$offset = $request['start'];
$length = $request['length'];
$order = $request['order'][0]['dir'];
// Search all columns
$sql_where = "";
if ( !empty($request['search']['value']) ) {
$sql_where .= "WHERE ";
foreach ($columns as $column) {
$sql_where .= $column . " LIKE '%" . sanitize_text_field($request['search']['value']) . "%' OR ";
}
$sql_where = substr($sql_where, 0, -3);
}
// Total Records in the datatable
$total_table_records = "SELECT count(*) as count FROM {$table_name}";
$total_fetched_records = $wpdb->get_results($total_table_records, OBJECT);
$total_records = $total_fetched_records[0]->count;
// Total Records Search
$total_table_records_search = "SELECT count(*) as count FROM $table_name $sql_where";
$total_fetched_records_search = $wpdb->get_results($total_table_records_search, OBJECT);
$total_records_search = $total_fetched_records_search[0]->count;
// Query
$total_results = $wpdb->get_results( "SELECT * FROM $table_name $sql_where ORDER BY $column $order LIMIT $offset, $length" );
if ( !empty($total_results) ) {
foreach ($total_results as $row){
$nestedData = array();
$nestedData[] = $row->ID;
$nestedData[] = $row->first_name;
$nestedData[] = $row->last_name;
$nestedData[] = $row->email;
$nestedData[] = $row->phone;
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval($request['draw']),
"recordsTotal" => intval($total_records),
"recordsFiltered" => intval($total_records_search),
"data" => $data
);
echo json_encode($json_data);
} else {
$json_data = array(
"data" => array()
);
echo json_encode($json_data);
}
wp_die();
}

Need to get the insert_id value and pass it to another PHP file

I have this form function in main.php file to save submitted data in the database using Contact Form 7 plugin. I need to get the $lastid value from this function below and pass it to query.php to update my query based on ID. How to do that?
main.php
function user_data_form( $wpcf7 ) {
global $wpdb;
$title = $wpcf7->title();
$form = WPCF7_Submission::get_instance();
if ($form) {
$data = $form->get_posted_data();
if ( $title == 'User Data' ) {
$name = $data['name'];
$email = $data['email'];
$bio = $data['bio'];
$url = $data['url'];
$wpdb->insert( $wpdb->prefix . 'user_data',
array(
'name' => $name,
'email' => $email,
'bio' => $bio,
'url' => $url
), array( '%s', '%s', '%s', '%s' )
);
$lastid = $wpdb->insert_id;
}
}
}
add_action( 'wpcf7_before_send_mail', 'user_data_form' );
define('ROOTDIR', plugin_dir_path(__FILE__));
require_once(ROOTDIR . 'query.php');
query.php
$wpdb->update( $wpdb->prefix . 'user_data',
array( 'status' => $status ),
array( 'ID' => $lastid ),
array( '%s' ), array( '%d' )
);
I tried to use array( 'ID' => $lastid ), but it kept returning to null.

If Statement Within A Nested Array

What I am trying to do is query a WordPress custom post type using meta keys from a search form. The search form takes user inputs and show the results based on the matching criteria, Some of the form's fields might be blank, so I need to make sure I don't pass any blank value to the query argument. I need to use if within the arguments array.
I'll be grateful for any type of help.
This is the code I am using, but getting an error message.
Parse error: syntax error, unexpected T_IF, expecting ')'
Here is my code:
if (isset($POST['stock']) && !empty($POST['stock'])) {
$stock = $POST['stock'];
}
if (isset($POST['mineral']) && !empty($POST['mineral'])) {
$mineral = $POST['mineral'];
}
if (isset($POST['species']) && !empty($POST['species'])) {
$species = $POST['species'];
}
if (isset($POST['color']) && !empty($POST['color'])) {
$color = $POST['color'];
}
if (isset($POST['chemicalclass']) && !empty($POST['chemicalclass'])) {
$chemicalclass = $POST['chemicalclass'];
}
if (isset($POST['locality']) && !empty($POST['locality'])) {
$locality = $POST['locality'];
}
if (isset($POST['description']) && !empty($POST['description'])) {
$description = $POST['description'];
}
if (isset($POST['size']) && !empty($POST['size'])) {
$size = $POST['size'];
}
if (isset($POST['pricegt'])) {
$pricegt = $POST['pricegt'];
} else {
$pricegt = 0;
}
if (isset($POST['pricelt'])) {
$pricelt = $POST['pricelt'];
} else {
$pricelt = 999999;
}
$args = array(
'post_type' => 'products',
'productspecies' => $species,
'localities' => $locality,
'meta_query' => array(
//'relation' => 'OR',
array(
'key' => '_price',
'value' => array( $pricegt, $pricelt ),
'compare' => 'BETWEEN',
'type' => 'numeric',
),
if ($mineral) {
array(
'key' => '_components',
'value' => $mineral,
),
}
if ($stock) {
array(
'key' => '_lotnum',
'value' => $stock,
),
}
if ($color) {
array(
'key' => '_color',
'value' => $color,
),
}
if ($description) {
array(
'key' => '_smalldesc',
'value' => $description,
'compare' => 'LIKE',
),
}
if ($size) {
array(
'key' => '_size',
'value' => $size,
),
}
if ($chemicalclass) {
array(
'key' => '_chemicalclass',
'valeu' => $chemicalclass,
),
}
),
);
?>
<?php $query = new WP_Query( $args ); ?>
<div class="postcount">We Found A Total Of <span><?php echo $query->post_count;?></span> Items Maching Your Search</div>
<?php if ( $query->have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
What I am doing wrong?
You are trying to pass if statements as arguments to the array() function. PHP does not allow that. One thing you can do is build the array without the optional parts and then add them later if necessary:
if ($stock) {
$args['metaquery'][] = array(
'key' => '_lotnum',
'value' => $stock
);
}
You can't insert instructions in the array initialization code.
Do it this way:
$args = array();
if (something){
$args['metaquery'][] = array(contentsOfTheInnerArray);
}
if (something2){
$args['metaquery'][] = array(contentsOfTheInnerArray2);
}
Not completely sure if this works (in php that is) but you can do something like this:
$array = array(
'price' => isset($POST['pricegt']) ? $POST['pricegt'] : 0,
...
);

Combining Multiple foreach Result in json_encode

I am trying to get the following json_encode output:
The Array:
echo json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "2012-8-10",
'end' => "2012-8-15",
'url' => "http://yahoo.com/",
),
array(
'id' => 222,
'title' => "Event2",
'start' => "2012-8-20",
'end' => "2012-8-22",
'url' => "http://yahoo.com/"
)
));
OUTPUT:
[{"id":111,"title":"Event1","start":"2012-8-10","end":"2012-8-15","url":"http:\/\/yahoo.com\/"},{"id":222,"title":"Event2","start":"2012-08-20","end":"2012-08-22","url":"http:\/\/yahoo.com\/"}]
However, when I am using the following code
global $wpdb;
$row = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_title FROM $wpdb->posts WHERE $wpdb->posts.post_type = 'calendar' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.post_date ASC");
foreach ($row as $post) {
$postid = $post->ID;
$post_title = $post->post_title;
$startDate = get_post_meta($post->ID,'calendar_start-date',true);
$endDate = get_post_meta($post->ID,'calendar_end-date',true);
$link = get_post_meta($post->ID,'calendar_link',true);
$arr = array('id' => $postid, 'title' => $post_title, 'start' => $startDate, 'end' => $endDate, 'url' => $link);
echo json_encode($arr);
}
I get the output as
{"id":"320","title":"Test Event One","start":"2012-8-17","end":"2012-8-24","url":"http:\/\/www.yahoo.com"}{"id":"321","title":"Test Event Two","start":"2012-8-21","end":"2012-8-30","url":"http:\/\/www.google.com"}
I understand it is probably due to the json_encode being inside the foreach loop. However when I try it outside, it only shows the first result. How to combine these foreach values to achieve the output as mentioned above?
you could use this:
global $wpdb;
$posts = array();
$row = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_title FROM $wpdb->posts WHERE $wpdb->posts.post_type = 'calendar' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.post_date ASC");
foreach ($row as $post) {
$postid = $post->ID;
$post_title = $post->post_title;
$startDate = get_post_meta($post->ID,'calendar_start-date',true);
$endDate = get_post_meta($post->ID,'calendar_end-date',true);
$link = get_post_meta($post->ID,'calendar_link',true);
$arr = array('id' => $postid, 'title' => $post_title, 'start' => $startDate, 'end' => $endDate, 'url' => $link);
$posts[] = $arr;
}
echo json_encode($posts);
I think that should work

Categories