Get information from specific row of most recently inserted database entry - php

Apparently this...
$lastid = $wpdb->insert_id
...will give me the last inserted row (as noted here: How to get last inserted row ID from wordpress database?).
But how can I target a specific table, and get information from the latest inserted row after a form was just submitted?
For example, I have a table called 'license' and each row contains the columns 'email' and 'name' (among others).
The idea is that after I insert something into that row with a form, I need to display the email and name on screen.
Any help would be awesome.

You can use the value of an auto-increment column.
You might already have the ID column doing so.
In a new SELECT-statment use ORDER BY myCol DESC the auto-increment-coloumn and use LIMIT 1 to only get the one with the highest value (wich is the most recent one)

According to what you already have you have to use the last inserted id for a new query.
$query = "select * from license where id = ".$lastid;
Using the result of this query you can print out the other information of the last inserted row.
If you need more info on the php code, provide your code so we can edit it accordingly

ID of the Last Inserted Record in general (in your example from Wordpress), can only fetch (as the name says) only the ID (AUTO_INCREMENT) from a column as a result of the most recently executed INSERT statement. mysql doc
There is no direct way if specifying "get me lastID of XYZ table" for a particular in reverse point in time, only works as described above.
Even with the proper usage in php you need to be careful if other INSERT statements on other tables (ones you don't want) are executed before you try to fetch LAST_INSERT_ID, so you don't end up getting IDs from unwanted tables.
Your possible workarounds:
do a SELECT from your desired table ordered by ID desc, e.g:
SELECT id FROM xyz ORDER BY id DESC LIMIT 1;
this is presuming id is an AUTO_INCREMENT or similar
another option is if possible in code locate the "position" of INSERT statements of the table you want e.g. xyz and fetch the id right there with:
$wpdb->insert_id

Related

Display original and duplicate data from MySQL

I have a table with the following columns:
id
name
mail
There is lot of data in this table and chances of duplicate data is very high.
I want to display original data row and duplicate data row one after other so that user can delete duplicate data on clicking delete button.
if you select the data and only order them by email address, the original and the duplicates will come together. The rest of the logic can be covered in PHP too.
First of all there is no provision to detect original and dubplicate records in my sql. group by can give u dublicate entry of same record if any there.
You can use group by mail having count(id) > 1 in your select query to find out the records which are duplicate. Then you can use this query result as sub query and find out all records which are duplicate and order them base on mail.

Inserting an ID from one table into another when a new record is inserted

I have a form, which contains an employees personal information. I update the form, and it inserts into a table, called employee_info. It updates the table with the details and inserts a NEW ID(employee_id). In my database, I have another table called department_info, and the field which is relevant is department_id. This is the php markup, for inserting data into the database:
$sql_data_array = array('employee_firstname' => $employee_firstname); //other variables go here
if (ACCOUNT_DOB == 'true') $sql_data_array['driver_dob'] = tep_date_raw($driver_dob);
tep_db_perform(TABLE_EMPLOYEES, $sql_data_array);
$employee_id = tep_db_insert_id();
What I need to do is, when the form is updated, and data is inserted into the employee_info table, I need it to insert a new id for employee_id(which is already happening), and also to insert the department_id into the employee_info table.
The department_id is used to login, and I want to show a list of the employees, which belong to the department. Can anyone tell me how I would do this?
When you insert with PHP, most of the implementations return so called last insert id. This is a value of AUTO_INCREMENT column.
Even if your implementation does not support it, there should be a function that returns it.
EDIT:
From your update, this seems to be osCommerce. The problem with your code is that method tep_db_perform is used to insert one or MORE elements. What will happen, if you insert 2 rows? But in simple case, use tep_db_insert_id(), it should return last id.
php function mysqli_insert_id retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). Get this id and use it in other tables.

Getting ID of the row as its being written - mysqli

Can this be done in a single query? The table has an auto increment field which I need to know the number to fill url field in the table.
Table
id(AI) | title | url
What I am expecting is something like
INSERT INTO table (title,url) VALUES ('name','CONCATENATION OF title AND ID');
I am currently doing this using 2 queries.
1.Writing the fields except URL.
Getting the id using mysqli_insert_id()
2.Updating the above written row.
P.S : The Table has other fields as well so changing the db design isnt really possible in this case.
It can't be done atomically. In theory, you could SELECT MAX(id) + 1 FROM yourtable, but please, please don't - although this is not guaranteed to give you the right result and is definitely not a safe approach.
This seems like bad practice, anyway. Why not concatenate the title and ID when you fetch it? Why must it be concatenated on insert?
I will not comment on the design of your database -- you are the judge of that. Just bear in mind that the following command gets the next auto-increment-ID for the specified table, and that this number could change in an instant if another user accesses the table before your code can use it.
I am using this code myself in a project for a similar reason to your own, and it works for me because the table is updated only a few times per day and never by more than one person at a time.
SELECT Auto_increment FROM information_schema.tables WHERE
table_name = '$name_of_your_table';
To be clear, this code gets the auto-increment ID that will be given to the next table entry for the specified table.

splitting data into multiple tables

I am building a employees page.
Some of the information goes into an 'employees' table but some of it goes into a 'availability' table that is referenced to the 'employee' table:
availability:
id / employeeid (unique id from employees table) / monday available / and on and on /
So I don't have that unique ID from the employees table until I create them.
Is it fine to do a query where I set the employee info and then a query to get the last created row in the employee table and then use the unique id from that to set the availability...
Or is that messy and should I have a create employee page and THEN a set availability page?
So basically I want to know if it is cleaner and 'better' coding to separate the two functions?
Adding to #Quassnoi's answer:
You would add the employee record, then use the MySQL LAST_INSERT_ID() function to find the autoincremented unique id for the employee record you added. You can then feed that value back into the availability INSERT statement.
More details are on the MySQL manual page at http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
It's important that you not use a SELECT statement (e.g. SELECT MAX(employee.id)) since there might be other uses adding records as well. LAST_INSERT_ID() is specific to your connection
Of course create employee first, availability then.
If your tables are InnoDB, you can do it in a transaction so that you can rollback the whole update if something goes wrong.
Is it fine to do a query where I set
the employee info and then a query to
get the last created row in the
employee table and then use the unique
id from that to set the
availability...
Yes, that sounds OK. If you use an autoincrement column for employeeid, you can then use mysql_insert_id() or equivalent to retrieve that last inserted id safely. Don't do SELECT MAX(employeeid) FROM ...., because you might get problems when loads of people are using it concurrently.
You can easily get the last insered record via
mysql_insert_id()
After that, you can insert an availability record for the desired employee.
Note: I would choose a framework that takes care of these issues, like Symfony or Cake.
Using the "last created row" may not always work the way that you're expecting and may complicate things in the future if there's growth or if another programmer assumes the project. If I understand what you're looking for, you should instead have 3 tables. One table for employees, one table for availability, and a third table should be used to store unique records for the association. In the association table each row will have columns for : a unique ID, the employee id, the availability id.

Retrieving the index of an inserted row

I'm trying to keep the database tables for a project I'm working on nice and normalized, but I've run into a problem. I'm trying to figure out how I can insert a row into a table and then find out what the value of the auto_incremented id column was set to so that I can insert additional data into another table. I know there are functions such as mysql_insert_id which "get the ID generated from the previous INSERT operation". However, if I'm not mistaken mysql_insert_id just returns the ID of the very last operation. So, if the site has enough traffic this wouldn't necessarily return the ID of the query you want since another query could have been run between when you inserted the row and look for the ID. Is this understanding of mysql_insert_id correct? Any suggestions on how to do this are greatly appreciated. Thanks.
LAST_INSERT_ID() has session scope.
It will return the identity value inserted in the current session.
If you don't insert any rows between INSERT and LAST_INSERT_ID, then it will work all right.
Note though that for multiple value inserts, it will return the identity of the first row inserted, not the last one:
INSERT
INTO mytable (identity_column)
VALUES (NULL)
SELECT LAST_INSERT_ID()
--
1
INSERT
INTO mytable (identity_column)
VALUES (NULL), (NULL)
/* This inserts rows 2 and 3 */
SELECT LAST_INSERT_ID()
--
2
/* But this returns 2, not 3 */
You could:
A. Assume that won't be a problem and use mysql_insert_id
or
B. Include a timestamp in the row and retrieve the last inserted ID before inserting into another table.
The general solution to this is to do one of two things:
Create a procedural query that does the insert and then retrieves the last inserted id (using, ie. LAST_INSERT_ID()) and returns it as output from the query.
Do the insert, do another insert where the id value is something like (select myid from table where somecolumnval='val')
2b. Or make the select explicit and standalone, and then do the other inserts using that value.
The disadvantage to the first is that you have to write a proc for each of these cases. The disadvantage to the second is that some db engines don't accept that, and it clutters your code, and can be slow if you have to do a where on multiple columns.
This assumes that there may be inserts between your calls that you have no control over. If you have explicit control, one of the other solutions above is probably better.

Categories