MYsql - Get insert id - sql - mysql

I want to execute a query that insert the insert id to one of the colums
And I want to know how to get the insert id
I read this answer Get inserted id from mysql insert procedure
but its talk about how to get the insert id after the query, And I want to get it when I do the query
I try to do:
$stmt = $db->prepare("INSERT INTO `files` (`name`, `fname`) VALUES (?, LAST_INSERT_ID() + ?)") or die($db->error);
$stmt->bind_param('ss', $name, $uniqid);
But its dosent work, I always get 56, also the contcat dosent work, what I need to do?

It is simply easier and better to save it after the insert. It is also highly unlikely you will get the correct id before the actual insert happens.
The most reliable way would be to use transactions.
Start a transaction
Insert the row
Update the insert id
Commit the transaction

The + is not a string concatenation operator in MySQL. Use CONCAT(string1, string2, ...).
In the wire protocol, mysql returns the same value as LAST_INSERT_ID() to the client after each query, unsolicited, and most libraries provide a way to access the most recently returned value. You didn't mention, but it looks like you're using mysqli in php, so you're looking for this:
$last_id = $db->insert_id;
It may look as if this is going to send a second query to ask the database for the id, but it isn't. It's returning the previously stored value.
http://php.net/manual/en/mysqli.insert-id.php

Related

INSERT doesn't work when followed by SELECT LAST_INSERT_ID

There are a lot of questions about LAST_INSERT_ID()
In my case, issue is:
When INSERT is followed by SELECT LAST_INSERT_ID() there are no records being inserted
INSERT INTO sequences (state) VALUES (0);
select LAST_INSERT_ID();
>>> 80 // nothing is added to DB
INSERT on it's own works OK
INSERT INTO sequences (state) VALUES (0);
>>>
select LAST_INSERT_ID();
>>> 81 // row is inserted
For testing I am using SequelPro, DB is Amazon's RDS MySQL. Same issue happens when I use Python's MySQLdb module.
Ideally I want to insert row, get back ID of it for future identification and use.
You should run one query at a time. Most SQL interfaces don't allow multiple queries.
MySQL allows a single query to be terminated by ; but if there's any words following the ; (except for a comment), it's be a syntax error, which will make the whole request fail. So the INSERT won't run either.
MySQL does have a connection option to allow multi-query, but it's not active by default. See https://dev.mysql.com/doc/refman/8.0/en/c-api-multiple-queries.html
There's really no reason to use multi-query. Just run the SELECT LAST_INSERT_ID() as a separate query following the INSERT. As long as you use the same connection, it'll give you the right answer.

Place an Insert Statement into a Select Statement

I have read the other questions and all of the posted comments/answers to questions that are similar to this one. None of them seem to answer this question directly.
I am wanting to know if there is a way to either concatenate or place an INSERT, DELETE or UPDATE statement into a SELECT statement.
If so how? Could this be done by using a derived table function or a subSelect statement?
And example would be:
INSERT INTO Customer (name)
VALUES 'Test Name'
but place this into a SELECT statement
Example pseudo code:
SELECT *
FROM Customer
WHERE
Customer.name = (INSERT INTO Customer (name) VALUES 'Test Name')
The big thing here is getting the INSERT statement into the SELECT statement in an unconventional way.
Thank you and hopefully this will strike up some good conversation/ideas/results!
Reason for wanting to know this:
Our current DBMS (Fishbowl) does not allow us to use an UPDATE, DELETE or INSERT statement with is SQL compiler and we are wanting to mass alter our fields/clean up our tables.
To know if it is possible
You may have a select within an insert but not the other way
around.
A select within an insert statement could be used to copy values from a table to another. (You are just writing into a table after a read from another)
But an insert within a select doesn't make sense! What are you going to insert when you are running a select from a table(or just reading data)?(how is it possible to write when you are only allowed to read?)
Your situation, if you don't have access to run an insert then it doesn't matter where you put the statement, you just can't because you aren't allowed to!
But if you are talking about your query engine/database wrapper not allowing a direct insert, then its probably because it requires an application/program to insert data into to rather than just a query(as your engine doesn't already have the capability to perform that operation).

I need to find out who last updated a mysql database

I can get a last update time from TABLES in information_schema. Can I get a USER who updated the database or a table?
As Amadan mentioned, I'm pretty sure there isn't a way to do this unless you record it yourself. However, this is a pretty straightforward thing to do: Whenever you perform an UPDATE query, also log in a separate table the user (as well as any other relevant information) that you want to record via an additional MySQL query. Something like this (written in PHP as you didn't specify a language, but the MySQL can be exported anywhere) will work:
// The update query
$stmt = $db->prepare("UPDATE table SET `col` = ? WHERE `col` = ?");
$stmt->execute(array($var1, $var2));
// Something in table has just been updated; record user's id and time of update
$stmt = $db->prepare("INSERT INTO log (userid, `time`) VALUES (?, NOW())");
$stmt->execute(array($userid));

Return value by mysql_query for insert query

I am using mysql c api, I want to know that, is there any way so that I will come to know my insert query failed because I tried to insert duplicate value for primary key. I know I can retrieve existing entries and compare it with value which I want to insert but it will be better if I get to know it by return value of mysql_query.
Thanks in advance.

Mysql - Get auto increment id on actual insert

Does anyone know if it is possible to get the auto increment id of a field in a mysql table and use it in the same insert?
e.g
assuming the new id here would be 2, an evaluated statement would look as follows
"insert into table (field1) values( 'random-2')"
I know it's possible for me to return this in the code and run another insert, but I wondered if there was a quicker way to 'compute' this during the insert?
1 thought I had was "insert into table (field1) values( 'random' + (select max(id) FROM table) + 1)"
but I'm worried about possible issues with multiple inserts occurring at the same time.
Thanks
It's not possible. You're gonna have to update the entry afterwards.
I'm worried about possible issues with multiple inserts occurring at the same time
That's only part of the problem - insert ids are only suposed to be unique - not contiguous.
If you want to do it in a single call from the application then use a stored procedure to encapsulate the insert+update or use a trigger to fire an update on insert. Or use a sequence generator instead of an autoincrement.