How to insert and select data in the same SQL query? - php

I used query like this
INSERT INTO coins VALUES (NULL, '$user_ID', '$title', NOW())
now later in this same script page, I need to use value coin_ID that I just inserted in the query above. It's auto increment value so I added NULL.
how can I use this coin_ID in this same page, after I ran some checking with PHP?
thanks

mysql_insert_id in PHP or LAST_INSERT_ID in mysql

It depends on which database driver you are using with PHP. If you are using the standard mysql functions you can use the mysql_insert_id function:
$coin_id = mysql_insert_id()
If you are using PHP's PDO then you can use the lastInsertId() method:
$coin_id = $DB->lastInsertId()
If you are using a database that supports the RETURNS sql keyword (such as postgres) then you can do it in one query. MySQL doesn't support it however.
INSERT INTO coins VALUES (NULL, '$user_ID', '$title', NOW()) RETURNING coin_id;
If you edit your post to include the method of database interaction that you are using, we can provide a more specific answer.

See mysql_insert_id.

Use mysql_insert_id to retrive last inserted ID.

$coin_ID = mysql_insert_id();

Try using LAST_INSERT_ID() via the PHP mysql_insert_id function.

Related

SQL, how to get the automated ID from the previous INSERT?

I am using PHP and SQL and trying to insert user data into two tables upon registration. First in the user_table and second into the character_table. I'm using an automatically generating user_id to link the tables and need to get the value of the user_id from the first INSERT (into user_table) then add it to a column in the character_table.
I tried a few methods and here is where I ended ($username, $email, $password and $character are defined above);
$sql = "INSERT INTO
user_table (id, username, email, password)
VALUES ('NULL', '".$username."', '".$email."', '".$password."')
INSERT INTO
character_table (name, id)
VALUES ('".$character."', 'LAST_INSERT_ID()')";"
I want "id" from user_table to match with "id" inserted into character_table.
When I run the above, nothing seems to be happening. Previous attempts I always ended with id = 0. What is the correct way I can get the ID from the first INSERT?
Run your statements seperately. You run your insertion into your user_table, then grab the id then run your insertion into your character_table
You can grab the id using mysql_insert_id after running the insert. Note that on the php webpage detailing the mysql_insert_id function that it is deprecated as is all mysql* functions. Which leads to...
For the love of everything holy don't concatenate your variables directly to your INSERT statement. Switch to mysqli* functions or PDO if you haven't already and use prepared statements (parameterizing the query). If you build an application using mysql it means you are not parameterizing your queries which means you are at a huge risk for a sql injection attack.
If/when you switch over to mysqli or PDO functions you will find an equivalent mysqli_insert_id() (or PDO::lastInsertID()) function

how to insert data into 2 different tables (php mysql)

2 Tables:
1. BOOKS_IN
BOOKS_in_ID,
DATE,
USERID
2. BOOKS_IN_DETAIL
BOOKS_in_ID,
BOOK_ID,
STOCK
BOOKS_in_ID is a primary key and i need BOOKS_in_ID is automatically insert into BOOKS_IN_DETAIL.
Here, is it possible to insert records into 2 table using single query?
thankyou for your advise.
You need to call the appropriate method to get the last inserted id.
Assuming you use PDO, you need to call the method lastInsertId. $books_in_id = $pdo->lastInsertId();
If you use mysqli_* extension that's $books_in_id = $mysqli->insert_id;
EDIT: if you use the mysql_* version ( which is deprecated), upgrade first to mysqli_* , or check in the documentation
You still need two INSERT statements, but it sounds like you want to get the IDENTITY from the first insert and use it in the second, in which case, you might want to look into OUTPUT or OUTPUT INTO: http://msdn.microsoft.com/en-us/library/ms177564.aspx
Src and possible duplicate of: SQL Server: Is it possible to insert into two tables at the same time?
You can also use LastInsertId() for PDO.
A small example:
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
Src: http://php.net/manual/en/pdo.lastinsertid.php
Or get the last insert ID in mysqli:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
Src: http://php.net/manual/en/mysqli.insert-id.php
Do you have to stick to mysql? Because if you can use mysqli you can use multi_query(), which lets you execute multiple queries at once.
Link : http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
No,Its not possible with only one INSERT query.
You can follow these steps
Write two different queries and execute them
Create Stored Procedure that execute two INSERT queried
For point One you can useLAST_INSERT_ID() function to add foreigh key

PDO: Is lastInsertId() a separate query?

If I have this code:
<?php
$q = $sql->prepare("INSERT INTO `table` (row) VALUES ('1')");
$q->execute();
$lastid = $sql->lastInsertId(); // is this a 2nd query?
?>
Would it run as two separate SQL queries?
If so, is there a way to do it in one?
$lastid = $sql->lastInsertId();
it works like a query because it will select from database the last inserted id.
as the documentation said
Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.
No, in fact it doesn't run an SQL query.
Here's the line from ext/pdo_msyql/mysql_driver.c:
char *id = php_pdo_int64_to_str(mysql_insert_id(H->server) TSRMLS_CC);
This is a call to the MySQL API, mysql_insert_id(). This internally accesses the last insert id as a property, not by running SQL.

How to get id of just-executed sql query (in php)

In php I have an INSERT query to database. This query add some issue to database. I want to check if issue was added fine (there are some cases when issue doesn't added - without any mistake reporting). How to check this?
I have an idea, that after i make INSERT query i should make a query, for example: SELECT ..... WHERE id=last_id. But how to get the last_id - how to get id of last INSERT query? (id is autoincrementing sql field)
Thank you
mysql_insert_id();
You may find the answer to this StackOverflow question useful:
SQL - INSERT and catch the id auto-increment value
mysql_insert_id()
More info at http://php.net/manual/en/function.mysql-insert-id.php and http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
mysql_insert_id function returns id of previously inserted record.
I assume you're working with MySQL

Get autoincrement id after an insert query performed with a prepared statement

If I execute an insert query with a stored procedure with php and the mysqli_* functions, is there a way to retrieve the value of an autoincrement id field?
mysqli->insert_id does not seem to work.
Are you sure the last query you preformed was an INSERT?
mysqli->insert_id seems the proper answer:
Return Values
The value of the AUTO_INCREMENT field that was updated
by the previous query. Returns zero if
there was no previous query on the
connection or if the query did not
update an AUTO_INCREMENT value.
You could try to make a query to MySql like so:
SELECT LAST_INSERT_ID()
Not sure if it works with stored procedures though.
You could add this statement in your stored procedure after the insert:
SET #saved_id = LAST_INSERT_ID()
Then, execute this query after calling the procedure:
SELECT #saved_id
mysqli->insert_id (where mysqli represents your database connection)
must be used directly after the insert. If you run other queries on the same connection
before attempting to read insert_id you get 0 returned.

Categories