$wpdb insert not working - mysql

I've created a new meta box for my 'cases' post type. And when I publish a new 'cases' post I want to insert the meta id into a new table created by me called 'sort'. I used this code:
function save_postdata( $post_id ) {
global $post, $new_meta_boxes, $wpdb;
foreach ($new_meta_boxes as $meta_box) {
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( 'cases' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
$data = $_POST[$meta_box['name'].'_value'];
if(get_post_meta($post_id, $meta_box['name'].'_value') == "") {
add_post_meta($post_id, $meta_box['name'].'_value', $data, true);
$meta_id = get_post_meta($post_id, 'meta_id', true);
$wpdb->insert( 'sort', array('meta_id'=>$meta_id, 'column_order' => 1));
}
elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
update_post_meta($post_id, $meta_box['name'].'_value', $data);
elseif($data == "")
delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));
}
}
The sort table has three fields: id, meta_id and column_order. Can someone sees what I'm doing wrong?

Make sure that on your insert statement you add 'NULL'
$wpdb->insert( 'sort', array('NULL', 'meta_id'=>$meta_id, 'column_order' => 1));
This could be causing the issue, and also make sure that it's the correct order of your columns.

Related

Wordpress: Adding multiple category-names & tag-names from page to <body>

Please refer to code below.
I have already a code who gives category-names and tag-names to the <body>. But it only puts in one category and one tag, not all. What do i have to update in my code to tell wordpress that it should get all tags and categories and put that as 'class' into the <body>?
// category-name to body
function add_category_name($classes = '') {
if( is_page() )
{
$category = get_the_category();
$classes[] = 'category-'.$category[0]->slug;
}
return $classes;
}
add_filter('body_class','add_category_name');
// tag-name in body
function add_tag_name($classes = '') {
if( is_page() )
{
$tag = get_the_tags( $post->ID );
$classes[] = 'tag-'.$tag[0]->slug;
}
return $classes;
}
add_filter('body_class','add_tag_name');
Thank you!
SOLUTION
You can add this code to your custom functions.php file:
// add tags and categories to pages
function add_taxonomies_to_pages() {
register_taxonomy_for_object_type( 'post_tag', 'page' );
register_taxonomy_for_object_type( 'category', 'page' );
}
add_action( 'init', 'add_taxonomies_to_pages' );
if ( ! is_admin() ) {
add_action( 'pre_get_posts', 'category_and_tag_archives' );
}
function category_and_tag_archives( $wp_query ) {
$my_post_array = array('post','page');
if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
$wp_query->set( 'post_type', $my_post_array );
if ( $wp_query->get( 'tag' ) )
$wp_query->set( 'post_type', $my_post_array );
}
// add tags and categorys as class to <body>
function add_categories_and_tags( $classes = '' ) {
if( is_page() ) {
$categories = get_the_category();
foreach( $categories as $category ) {
$classes[] = 'category-'.$category->slug;
}
$tags = get_the_tags();
foreach( $tags as $tag ) {
$classes[] = 'tag-'.$tag->slug;
}
}
return $classes;
}
add_filter( 'body_class', 'add_categories_and_tags' );
Works perfect, tested in WordPress 4.8

Count number of views for each user

I have table 'viewlogs' which is formed from three field: ViewLogId, VideoId and UserId. ViewLogId has a primary key and AUTO_INCREMENT value. When a user watches a video its value increments. When a user watch a same video the viewLogId increments, but I want this value to increase only once and uniquely. How do I fix this problem. I've attached the table picture.
I used the following php code for updating the view_counts in the "videos" table. The above picture belongs to the viewlogs table.
public function updateStatistics($videoId, $fieldName, $userId)
{
$this->db->reconnect();
$this->db->trans_begin();
$this->db->query("UPDATE videos SET {$fieldName}={$fieldName}+1 WHERE VideoId=?", array($videoId));
if ($fieldName == "ViewCount" && $userId > 0) {
$this->db->insert('viewlogs', array('UserId' => $userId, 'VideoId' => $videoId, 'ViewDateTime' => date('Y-m-d H:i:s')));
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
return false;
}
I solved the problem, just need to check the user_id and video_id before updating the view.
public function updateStatistics($videoId, $fieldName, $userId)
{
$this->db->reconnect();
$this->db->trans_begin();
$sql = "SELECT * FROM viewlogs WHERE UserId ={$userId} AND VideoId ={$videoId}";
$query = $this->db->query($sql);
$result = $query->result_array();
if (empty($result)){
$this->db->query("UPDATE videos SET {$fieldName}={$fieldName}+1 WHERE VideoId=?", array($videoId));
if ($fieldName == "ViewCount" && $userId > 0) {
$this->db->insert('viewlogs', array('UserId' => $userId, 'VideoId' => $videoId, 'ViewDateTime' => date('Y-m-d H:i:s')));
}
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
return false;
}

wordpress json rest API to get custom field data

I am currently using the JSON REST API (WP API) plug-in to get my post and page data.
I have noticed that none of my custom field data is returned in the json, and looking at the routes, i don't think i can obtain these.
Any ideas via the current plug-in, or how I can accomplish this otherwise?
If you are using 'advanced custom fields' - until something more official is decided, you can use this plugin: https://github.com/times/acf-to-wp-api (and now on the shelf in standard wp plugin area too.)
It will include the custom fields under acf: [], in your json structure.
To grab a custom field value using native WP functions only, add the following to your functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Replace 'my_custom_field_key' with your custom field key name.
For multiple fields:
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
// My custom fields that I want to include in the WP API v2 responce
$fields = ['writer', 'publisher', 'year', 'youtube_link'];
foreach ( $fields as $field ) {
$_data[$field] = get_post_meta( $post->ID, $field, true );
}
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
You need to create this file contain following code in
wp-content\themes\name\inc\functions
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/*
* init function
*/
if ( ! function_exists( 'mnu_rest_init' ) ) {
function mnu_rest_init() {
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'GET',
'callback' => 'handle_get_all',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'POST',
'callback' => 'handle_post_booking',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
}
}
//GET QUERY PARMS
function handle_get_all( $request_data) {
$parameters = $request_data->get_params();
$userId = $parameters["Id"];
global $wpdb;
$query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
$list = $wpdb->get_results($query);
return $list;
}
// GET BODY PARMS
function handle_post_booking( $request_data) {
$parameters = $request_data->get_body();
$params = json_decode( $parameters , true );
// $userId = $parameters["Id"];
// global $wpdb;
// $query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
// $list = $wpdb->get_results($query);
return $params ;
}
then you need to add
//actions
add_action( 'rest_api_init', 'mnu_rest_init');
to your main.php in
wp-content\themes\name\inc\functions
to do that you need to require this file to main.php
require_once dirname( __FILE__ ) . '/filename.php';
You can manipulate the response and add custom fields to the JSON. I'm using Advanced Custom Fields in my example but you can just add any key/value-pairs to the data object before returning it.
// In functions.php
function modify_rest_post( $data, $post, $request ) {
if (is_admin()) {
return $data;
}
$data->my_favorite_data = get_field('my_custom_field', $post->ID);
return $data;
}
add_filter( 'rest_prepare_post', 'modify_rest_post', 10, 3 );

Insert Data to Database Codeigniter only if item does not exit

I'm having trouble trying to insert batch data.
All is fine with the insert_batch function but i would like to insert only the items that does not exist in database, not update it, just ignore and insert new items.
This is my Controller:
csv file:
col0,col1,col2,col3
data1,data1,data1,data1
data2,data2,data,2,data2
data3,data3,data3,data3
insert batch:
function mres($q) {
if(is_array($q))
foreach($q as $k => $v)
$q[$k] = $this->mres($v); //recursive
elseif(is_string($q))
$q = mysql_real_escape_string($q);
return $q;
}
function inserbatch(){
$csv = 'file.csv';
$arrResult = array();
$handle = fopen("uploads/csv/".$csv, "r");
if( $handle ) {
while (($row = fgetcsv($handle, 0, ",")) !== FALSE) {
$arrResult[] = array(
'col0' => $row[0],
'col1' => $row[1],
'col2' => $row[2],
'col3' => utf8_encode($row[3])
);
}
fclose($handle);
}
$final = $this->mres($arrResult);
$this->model_m->addBatch($final);
}
Model:
public function addBatch($final = array()){
if($this->db->insert_batch('mytable', $final)){
return true;
}
return false;
}
database:
id,col0,col1,col2,col3
col0 contain the unique value and if exist in csv file need to be skipped.
My question is how can i insert only the data that doesnt exist in database the col0 is the unique value and i think need to be like
if data from csv[col0] != database[col0] insert_batch.
Any help is appreciated.
Yes I think you on the right path. You only need to check your db if the value exists.
Something like this:
foreach(csv[col0] as $your_data)
{
$query = $this->db->query("SELECT * FROM my_table WHERE col0 = $your_data");
$rows = $query->num_rows();
if(!$rows)
{
// No record has been found so here you would write the code to insert the data
}
}

moving specific field value to another table before deleting the whole row

I have a table with 7 fields, when I delete a row from the table by id i want two fields of that row to be inserted into another table with just two columns.
This is my controller function
public function refund() {
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}
these are model functions
public function delete_accounts_data($id) {
$this->db->where('id', $id);
$this->db->delete('accounts');
}
public function insert_refund($data){
$this->db->insert('refund', $data);
}
Suppose this the row i will delete
id|name|barcode|refunded_amount|commission
01|asd |2342342| 53.01 | 5.32
on the other hand i will insert as
id|barcode|refunded_amount
01|2342342| 53.01
You should try and debug your code for general errors, e.g,
1) Try to set the environment to development in index.php.
2) Add some debugging code in your function to check for errors.
function refund(){
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
echo $this->db->last_query(); //will produce the query for fetching the details by id
if( isset( $accounts ) && count( $accounts ) > 0 ){
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
print_r( $data );
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}else{
echo "NO DATA FOUND";
}
}