How to get last inserted row ID from WordPress database? - wordpress

My WordPress plugin has a table with a AUTO_INCREMENT primary key field called ID. When a new row is inserted into the table, I'd like to get the ID value of the insertion.
The feature is to using AJAX to post data to server to insert into DB. The new row ID is returned in the AJAX response to update client status. It is possible that multiple clients are posting data to server at the same time. So, I have to make sure that each AJAX request get the EXACT new row ID in response.
In PHP, there is a method called mysql_insert_id for this feature.But, it is valid for race condition only if the argument is link_identifier of last operation. My operation with database is on $wpdb. How to extract the link_identifier from $wpdb to make sure mysql_insert_id work? Is there any other way to get the last-inserted-row id from $wpdb?
Thanks.

Straight after the $wpdb->insert() that does the insert, do this:
$lastid = $wpdb->insert_id;
More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page

This is how I did it, in my code
...
global $wpdb;
$query = "INSERT INTO... VALUES(...)" ;
$wpdb->query(
$wpdb->prepare($query)
);
return $wpdb->insert_id;
...
More Class Variables

I needed to get the last id way after inserting it, so
$lastid = $wpdb->insert_id;
Was not an option.
Did the follow:
global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');

Get the last inserted row id in WP like this.
global $wpdb;
$order = ['product_name'=>'Computer', 'os_system'=>'Linux'];
$wpdb->insert('wp_product_orders', $order );
$last_inserted_id = $wpdb->insert_id;

Something like this should do it too :
$last = $wpdb->get_row("SHOW TABLE STATUS LIKE 'table_name'");
$lastid = $last->Auto_increment;

just like this :
global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);
simply your selecting all the rows then order them DESC by id , and displaying only the first

Putting the call to mysql_insert_id() inside a transaction, should do it:
mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

Related

wordpress query builder (typerocket) get post with relationship table data

I'm trying to get some post 'wp_posts.post_type', 'servitod_plan' in this case there are only 2 plans with that post_type. these posts have associated some wp_postmeta . when I try to bring each post, with the data of its relationship with postmeta brings me duplicates. when I look at the record it brings me
one object for each wp_postmeta.meta_key
I only want to bring the posts that correspond to 'wp_posts.post_type', 'servitod_plan' and their relation wp_postmeta of key name: value in this case plan_fee: 3000, etc.
My Controller.
$query = tr_query()->table('wp_posts');
$query->setIdColumn('ID');
$results = $query->select('wp_posts.post_name', 'wp_posts.ID', 'wp_postmeta.meta_value')
->join('wp_postmeta', 'wp_postmeta.post_id', '=', 'wp_posts.ID')
->where('wp_posts.post_type', 'servitod_plan')
->get();
return $results; // for develpment and test
MY WP_POSTMETA TABLE
MY WP_POSTS TABLE
when i see the RETURN DATA $RESULTS
You can just pass one more ->where('wp_posts.ID', 2271) and you can pass post id. check the below code.
$query = tr_query()->table('wp_posts');
$query->setIdColumn('ID');
$results = $query->select('wp_posts.post_name', 'wp_posts.ID', 'wp_postmeta.meta_value')
->join('wp_postmeta', 'wp_postmeta.post_id', '=', 'wp_posts.ID')
->where('wp_posts.post_type', 'servitod_plan')->whereIn('wp_posts.ID', 2271)
->get();
return $results; // for develpment and test
Update
for multiple ids you can use like ->whereIn('wp_posts.ID', array('2271','2269' ) )

Get the latest order ID after placed order in woocommerce

I want get the last order ID done after the placed order. I have used this for get the last order id.
global $wpdb;
$results = $wpdb->get_results( ' SELECT * FROM `wp_woocommerce_order_items`
ORDER BY `wp_woocommerce_order_items`.`order_item_id` DESC
LIMIT 1', OBJECT );
But apart from this, is there any other woocommerce function or hook to get the last order ID.
Thanks in advance.
If you just placed an order and nothing else then you can use ' $wpdb->insert_id'.. it will do the trick.

Select custom meta (WPAlchemy) from pages with wpdb

I have read some documentation and comparable questions from others about my issue with wpdb, but I've seen very different answers so I'm slightly confused.
What I'm trying to do is get custom meta data from (eventually) about 250 pages in Wordpress. The wpdb request will be in header.php, and the code has to build an array which will serve as input for a Google Map. The custom meta fields are called _ytF_f_name, _ytF_f_lat and _ytF_f_lng (don't ask me why :-)).
So the final output should be: [name1,lat1,lng1], [name2,lat2,lng2], etc.
I'm using a custom table for Wordpress, which has the prefix yt_ (which is defined in wp-config.php). The custom meta is built with WPAlchemy. I have checked the database and the meta data is there (in the postmeta table).
After combining several things, this is what I have now:
<?php
global $wpdb;
$querystr = "SELECT ".$wpdb->prefix."postmeta._ytF_f_name, ".$wpdb->prefix."postmeta._ytF_f_lat, ".$wpdb->prefix."postmeta._ytF_f_lng FROM ".$wpdb->prefix."postmeta WHERE post_type='page'";
$vars = $wpdb->get_results($querystr);
foreach ($vars as $var) {
echo '[' . $var->_ytF_f_name . ',' . $var->_ytF_f_lat . ',' . $var->_ytF_f_lat . '],';
}
?>
The output is blank, so what am I missing here?
Another question related to this is; I've read something about 'prepare' to protect against sql injections.
Is the correct use of the prepare class to change
$vars = $wpdb->get_results($querystr);
into:
$vars = $wpdb->get_results($wpdb->prepare($querystr));
?
About your problem, I don't see the error, so verify if you have SQL errors with $wpdb->show_errors(); before your query (doc here).
The prepare method protects you against SQL injections.
As the doc said, it works like the following :
$wpdb->query(
$wpdb->prepare(
"INSERT INTO ___
( attr1, attr2 )
VALUES ( %s, %d )",
$valueOfAttr1,
$valueOfAttr2
)
);
Of course, you must change the types and values to your needs.

Wordpress custom field in post database

I have added a field in wordpress posts table named "parent_location". How to get the value of this field in db front end? I have tried get_post_custom_values('parent_location', $post_id) function but it not working. Can any body help me out?
Thanks in advance, don't down vote
You added the field as a new column in wp_posts or added a new metadata entry to a single post? If its to a post then just do a get_post_meta(postID, 'parent_location', true); It its a new column into wp_posts, then should you not be able to just to a standard;
<?php
$my_id = 100;
$post = get_post($my_id);
$parent_loc = $post->parent_location;
?>
Not sure if that will work, I've not tried to get a custom column via that method before. If it doesn't, just roll your own SQL query; http://codex.wordpress.org/Class_Reference/wpdb

Wordpress - Delete all tags by Post ID

I've got a function to add a tag by post ID, but now I would like to delete all the current tags for that ID before adding my new tags?
Does anyone know a built in function or wordpress query to do this?
-Hudson
If you can access the database directly (PhpMyAdmin), the quickest way is a SQL request.
Look at the database schema in the codex :
DELETE FROM wp_term_relationships
WHERE wp_term_relationships.object_id = 'yourPostId'
AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
AND wp_term_taxonomy.taxonomy = 'post_tag';
WARNING : obviously, modifying directly the database is dangerous. Be careful doing that.
Should help you get there:
Wordpress API: Add / Remove Tags on Posts
I found this function: wp_delete_term See if it helps you...
I pieced this together. Its pure database work, because I believe there is no quick function to delete a tag via ID, (but I am still not 100% certain).
//define array of tags
$tags = array("new tag","new tag 2");
//define post ID
$val = 254;
//delete tags associated to post id
$query = "SELECT * FROM ".$table_prefix."term_relationships tr JOIN ".$table_prefix."term_taxonomy tt ON tr.term_taxonomy_id=tt.term_taxonomy_id WHERE tr.object_id='$val' AND tt.taxonomy='post_tag'";
$result = mysql_query($query);
if (!$result){echo $query; echo mysql_error();}
while ($arr = mysql_fetch_array($result))
{
$tid = $arr['term_taxonomy_id'];
$query2 = "DELETE FROM ".$table_prefix."term_relationships WHERE term_taxonomy_id='$tid'";
$result2 = mysql_query($query2);
if (!$result2){echo $query2; echo mysql_error();}
}
//add tags to post id
wp_add_post_tags($val,$tags);

Resources