Insert Where Clause in $wpdb->insert [duplicate] - php

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

How to get the ID of the last insert in MVC?

I have a $mydata->save(); in my statement to insert a new row, and the next row in the action I need the ID of the inserted row. How can I get it?
$id=$this->db->insert_id();
To get the last inserted id.
If $myData is a model then :
$result = $myData->save();
$id = $result->id;
Kind of same like in Laravel.
Although if you are using some MVC CMS like Joomla then it should be like:
$db = JFactory::getDBO();
$db->setQuery( $query );
$db->query();
$id = $db->insertid();
And also if you have liberty to run raw queries then simply use:
mysql_insert_id();
So it really depends upon you particular situation.

mysql query only selecting first record

I am trying to execute the query to update the record in php.My php code is this:
$get_meals_info = "Select meal_id from orders WHERE order_id ='$order_id'";
$result = mysql_query($get_meals_info) or die(mysql_error());;
if(mysql_num_rows($result)!=0)
{
while($meal_id = mysql_fetch_assoc($result)) {
$id= $meal_id['meal_id'];
//$update_status="Select meal_id from orders where order_id=" . $meal_id['order_id'] . "";
$update_status = "update order_main SET STATUS='$order_status' WHERE id =" . $meal_id['meal_id'] . "";
$result = mysql_query($update_status);
//$meal_id=null;
echo $id;
}
I first get all the meal ids related to one order in my first select query and then i try to update the status for each meal using while loop but what i get only first meal record updated not the other one.I get this reponse:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\learning\service\update_order_status.php on line 13
true
You're using the same variable $result for both your data fetching and update, and the first update causes you to lost the original data and then $result only contains true instead of the resource.
Why are you using a loop for this? You can accomplish this using a single query. For instance:
update order_main
SET STATUS = '$order_status'
WHERE id IN (Select meal_id from orders WHERE order_id = '$order_id');
Note also that you should be using mysqli_ functions and parameterizing the query so you are not passing user input in directly.

Use mysql_insert_id in single query

Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`

Show data from a specific row in MySQL

I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";

Need help for a specific MySQL query used in a PHP loop

The main code which i use is
while ($row = mysql_fetch_assoc($result1)) {
echo $row["user_id"];
$new = "[grade uid=\"{$row["user_id"]}\" value=\"{$groupgrade}\" format=\"{$groupformat}\" prv_comment=\"{$groupprivatecomment}\" pub_comment=\"{$grouppubliccomment}\"] ";
$sqq = "UPDATE wp_postmeta SET meta_value='$new' WHERE meta_key='grade' AND post_id= $post_id ";
$result = mysql_query($sqq);
echo "grade has been updated";
}
Which affects the rows in table wp_postmeta as shown in the picture on the link Where all the variables undefined here are defined before this para .
What i actually want that user id must be different in different rows.
The only thing happening in this loop is that each uid from the array gets written in all the rows one after the other and only the last uid persists finally which is 3 in the diagram but i only want that each uid should come separately i.e., differnt uid for diff. meta_id . Please help
REGARDING CODE
$result1 fetches an array of userids from a defined mysql function and rest variables are user defined.
I am kinda new to php and to programming so please help
The question is not very clear and it's WordPress related and you didn't add WordPress tag in your question. Anyways, WordPress has it's own function to handle post meta. In your loop you are trying to update post meta manually but it's possible to do that using WordPress' update_post_meta function. The syntax is given bellow
<?php update_post_meta($post_id, $meta_key, $meta_value, $prev_value); ?>
In this case you can use following code
<?php update_post_meta($post_id, 'grade', $new); ?>
Here $post_id will be your post id which you want to update.
OK, now that I understand your problem (you confused me by saying that "all rows" were being updated, you just mean all rows with this post_id), I think this is the answer:
$sql2 = "SELECT meta_id FROM wp_postmeta where meta_key='grade' AND post_id = $post_id";
$result2 = mysql_query($sql2);
while (($row = mysql_fetch_assoc($result1)) && ($row2 = mysql_fetch_assoc($result2))) {
echo $row2["meta_id"], ' => ', $row["user_id"];
$new = "[grade uid=\"{$row["user_id"]}\" value=\"{$groupgrade}\" format=\"{$groupformat}\" prv_comment=\"{$groupprivatecomment}\" pub_comment=\"{$grouppubliccomment}\"] ";
$sqq = "UPDATE wp_postmeta SET meta_value='$new' WHERE meta_key='grade' AND post_id= $post_id AND meta_id = {$row2["meta_id"]}";
$result = mysql_query($sqq);
echo " grade has been updated";
}
The new $sql2 query gets each meta_id, and updates each row with a different user_id from $result11.
your code is to work around this $row["user_id"]
if it same user who posted then the result will be true 3
if this variable is from other query then u must look to this query how u getting this user_id or , publish it in your question , to see why it comes only 3.
its better to make a column for user_id to insert data specialy for that user.
$row["user_id"] is beeing a warning variable to sql injection , so it must be escaped by mysql_real_escape_string()

Categories