$wpdb->insert_id is not working - mysql

I am trying to get the last inserted in id MySQL but it doesn't return anything. Row is getting inserted in the database and also $wpdb->last_query gives the last inserted query also.
Here is my code
global $wpdb;
$table_name = $wpdb->prefix . "request_from";
$wpdb->insert($table_name,
array('pre' => $prefix,
'first_name' => $first_name,
'middle_name' => $middle_initial,
'last_name' => $last_name,
'badge_name' => $name_badge,
'title' => $title,
'company' => $company,
'direct_mail' => $direct_mail,
'twitter' => $twitter_handle,
'direct_phone' => $direct_phone,
'address' => $address,
'address2' => $address_2,
'city' => $city,
'state' => $state,
'province' => $province,
'zip' => $zip_code,
'country' => $country,
'cc' => $cc,
'cc_contact' => $second_contact,
'cc_mail' => $second_email,
'cc_phone' => $second_phone)
);
$x= $wpdb->last_query;
$id = $wpdb->insert_id
I have a column called id with auto increment value
id int(11) No None AUTO_INCREMENT

Follow wpdb reference in Codex for troubleshooting:
enable database error display via $wpdb->show_errors()
check what query is being formed and run via $wpdb->last_query
Please check code by print or dump variable,
global $wpdb;
$table_name = $wpdb->prefix . "request_from";
$wpdb->insert($table_name,
array('pre' => $prefix,
'first_name' => $first_name,
'middle_name' => $middle_initial,
'last_name' => $last_name,
'badge_name' => $name_badge,
'title' => $title,
'company' => $company,
'direct_mail' => $direct_mail,
'twitter' => $twitter_handle,
'direct_phone' => $direct_phone,
'address' => $address,
'address2' => $address_2,
'city' => $city,
'state' => $state,
'province' => $province,
'zip' => $zip_code,
'country' => $country,
'cc' => $cc,
'cc_contact' => $second_contact,
'cc_mail' => $second_email,
'cc_phone' => $second_phone)
);
$x= $wpdb->last_query;
$id = $wpdb->insert_id;
// Let's output the last autogenerated ID.
echo $wpdb->insert_id;
// This returns the same result
echo mysql_insert_id();

Related

How to get WooCommerce products from database based on multiple attributes

I want to get related products based on some criteria on product attributes like, the same sku, ean and gtin codes. But my query doesn't return any results. I tried different ways to query the database but all fail. Here is my query.
$sku = $product->get_sku();
$ean = $product->get_attribute( 'EAN' );
$gtin = $product->get_attribute( 'GTIN' );
$query = new WP_Query( array(
'post_type' => array('product'),
'posts_per_page' => 20,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_sku',
'value' => $sku,
'compare' => '='
)
),
'tax_query' => array(
array(
'taxonomy' => 'pa_ean',
'field' => 'value',
'terms' => $ean,
'operator' => '=',
),
array(
'taxonomy' => 'pa_gtin',
'field' => 'value',
'terms' => $gtin,
'operator' => '=',
)
)
) );
By the way, if a product has ean code than it doesn't have a gtin and vice versa. It always has a sku which is unique to it self. But I have it added as a check to check if query at least returns value.
I can't find good documentary on this topic and hope someone here can help.

cakephp virtual fields with subquery and if

I have a Category table with a name field.
I want to be able to overwrite that name using a PartnerCategory Table and join it.
So usually I would get the Category like this:
$options = array(
'contain' => array('PartnerCategory'),
'conditions' => array(
'Category.slug' => $slug,
'Category.status' => true,
)
);
$category = $this->Category->find('first', $options);
And then check, if ParentCategory.name is not empty and replace the Category.name with it.
Overwriting the name with php is tedious so I checked virtual fields.
I can overwrite the Category.name using this:
$this->virtualFields = array(
'name' => 'SELECT name FROM app_partner_categories WHERE category_id = 1 AND partner_id = 60'
);
But if the name in the PartnerCategory table is empty or no mathes are found, the Category.name would be null.
How can I overwrite Category.name only if PartnerCategory.name is found?
Not sure but this could be a possible solution:
$joins = array(array('table' => 'app_partner_categories',
'alias' => 'PartnerCategory',
'type' => 'INNER',
'conditions' => array(
'PartnerCategory.category_id = Category.id'
)
)
);
$options = array(
'fields' => array('IF(PartnerCategory.name IS NULL or PartnerCategory.name = "", Category.name, PartnerCategory.name) as overwritten_name'),
'joins' => $joins,
'conditions' => array(
'Category.slug' => $slug,
'Category.status' => true,
)
);
$category = $this->Category->find('first', $options);

ACF Field query by Repeater Field not empty

Been reading up on info for querying ACF Fields in wordpress here, having trouble with this bit though:
$args = array(
'posts_per_page' => -1,
'post_type' => 'team_member',
'status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'patents',
'value' => array(''),
'compare' => 'NOT IN'
)
)
);
$the_query = new WP_Query($args);
Basically, just trying to query all posts that have an ACF Repeater field, called patents that has at least 1 patent inside of it. How to do this?
I just had to deal with this myself, and what ended up working for me was querying for all posts where the value of the repeater field was greater than 0.
$args = array(
'posts_per_page' => -1,
'post_type' => 'team_member',
'status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'patents',
'value' => 0
'compare' => '>'
)
)
);
Mark's answer to search for 'patents' = 1 only returned posts where the repeater field had one value.
http://www.advancedcustomfields.com/resources/the_repeater_field/
Try to access the repeater field first, then call the WP_Query. If you were to do something like:
if( get_field('repeater_field_name', $post_id) )
Then call the sub_field and/or in this case the WP_Query.
There is also this syntax, you can gather all the posts you need then scroll through posts:
if( have_rows('repeater_field') ):
while( have_rows('repeater_field') ) : the_row();
$sub = get_sub_field('sub_field');
Maybe you can call the wp_query on this level?
just check if the value is true
$args = array(
'posts_per_page' => -1,
'post_type' => 'team_member',
'status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'patents',
'value' => true,
'compare' => '='
)
)
);
$the_query = new WP_Query($args);
Try this ..
This is not the standard solution for achieving the target but it will
work
Get all the post IDs whose repeater field(s) are there
<?php
$args = array(
'posts_per_page' => -1,
'post_type' => 'team_member',
'status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
);
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( have_rows('patents') ){
$allowed_ids[] = get_the_ID();
}
}
}
/* Restore original Post Data */
wp_reset_postdata();?>
Then run another Loop to get only those posts by their IDS
$args['post__in'] = $allowed_ids;
$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$patents = get_field('patents');//array
}}

Fetch random row from group by query (mysql) in Cakephp

I have a table 'activities' and the columns are grouped by three of its attributes. Now I want to fetch Activity ID that is randomly selected from all the set of groups. The query is as follows:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
));
These are the things I tried and none of them worked.
1. Create a self join which should have random records
$this->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'Activity',
'order' => 'rand()',
'foreignKey' => 'id',
'fields' => 'Random.id'
)
)
));
This failed because the rand() order is appended in the end which simply randomizes all fetched activities.
Added a join option
'joins' => array(
array(
'table' => 'activities',
'alias' => 'Random',
'type' => 'LEFT',
'conditions' => array(
'Activity.id = Random.id'
),
'fields' => 'Random.id',
'order' => 'rand()'
)
This also didn't work as order value is not parsed by Cake
Tried to add condition
'Activity.id >= floor(rand() * (max(Activity.id) - min(Activity.id)) - min(Activity.id))'
Gave a mysql error
Please help me out
Assuming that your query is working:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
'order' => 'rand()',
'limit' => '1' // if you only want one random activity ID
));
Ok finally figured it out. We need to hack the way cake php works. In place of table name, I wrote a query to fetch randomly ordered records. Also notice the join type is 'right'. Left join wont produce randomly sorted list
$activities = $this->find('all', array('conditions' => $cond,
'page' => $page,
'limit' => $limit,
'fields' => array('count(*) as count, Random.id as id, max(Activity.modified) as Modified'),
'group' => $group,
'order' => 'Modified desc',
'joins' => array(
array(
'table' => '(select * from activities order by rand())',
'alias' => 'Random',
'type' => 'RIGHT',
'conditions' => array(
'Activity.id = Random.id'
),
)
)
));

join two model from one model in cakephp

i want to fetch record form 2 model (Booking and Message), both model don't have any relation.
i try a lot but its not working
i used that code ( http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables )
$options['joins'] = array(
array('table' => 'books_tags',
'alias' => 'BooksTag',
'type' => 'inner',
'conditions' => array(
'Book.id = BooksTag.book_id'
)
),
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'inner',
'conditions' => array(
'BooksTag.tag_id = Tag.id'
)
)
);
$options['conditions'] = array(
'Tag.tag' => 'Novel'
);
$books = $Book->find('all', $options);
Try this:
BookModel:
public $hasMany = array(
'BooksTag' => array(
'foreignKey' => 'book_id'
)
);
TagModel:
public $hasMany = array(
'BooksTag' => array(
'foreignKey' => 'tag_id'
)
);
BooksController:
$this->Book->Behaviors->load('Containable');
$this->Book->find('all', array(
'contain' => array(
'BooksTag' => array(
'Tag',
),
),
));
I prefer to do this on many queries. First find the required tag:
$this->loadModel('Tag');
$tag = $this->Tag->find('first', array('conditions' => array('Tag.tag' => 'Novel')));
$tag_id = $tag['Tag']['id'];
Then find book_ids:
$this->loadModel('BookTag');
$book_ids = $this->BookTag->find('list', array('conditions' => 'BookTag.tag_id' => $tag_id, 'fields' => 'book_id, book_id'));
Then find books:
$this->Book->find('all', array('conditions' => array('Book.id' => $book_ids)));
It is a long code but runs fast and is easy to understand. Another way is to use sub-queries but they are ugly and may slow down your application