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
Related
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 do I join these two queries and execute them as a single query to insert values in two tables:
$sql = mysql_real_escape_string('INSERT INTO admin_export(datetime, product_name, item_code,quantity,subject,export_no) VALUES').implode(',', $row_data);
$sql2 = "insert into `itflower_exportno` (admin_exportno) values('$exportno1')";
You need to separate your two INSERT statements with a semicolon into the single variable.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
You can however use transactions as following example.
BEGIN;
INSERT INTO users (username, password)
VALUES('test', 'test');
INSERT INTO profiles (userid, bio, homepage)
VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com');
COMMIT;
What you have in the code are two different inserts.
MySQL doesn't allow for multiple inserts to be run in the same query so you will have to do one first and then the other.
However you can insert multiple rows in the same table in just one query, basically you are restricted to do all the insert you want in one table at a time.
You can't do this.
If you want to do it because you are afraid of the integrity of the data, use transaction .
Second, use suitable transaction isolation level, to ensure that data are reading correctly.
i am inserting data from a form i want when i will insert data so the first column primary id which is using in second column as a foreign key should be increased
i have tried this code but not working
first table code
$this->db->query("insert into af_ads (ad_title,ad_pic,ad_description)
values ('$title','$filepath','$description')");
second table code
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category','ad_id')");
NOTE: i want to insert ad_id into ad_id_fk
Try this:
// Your first query
$this->db->query("insert into af_ads(ad_id, ad_title, ad_pic, ad_description)
values ('', '$title', '$filepath', '$description')");
$ad_id = $this->db->insert_id(); // This returns the id that is automatically assigned to that record
// Use the id as foreign key in your second insert query
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category', $ad_id)");
MySQL provides the LAST_INSERT_ID function as way to retrieve the value generated for an AUTO_INCREMENT column from the immediately preceding INSERT statement.
A lot of client libraries make this conveniently avaiable (e.g. PDO lastInsertId function.)
(I'm not familiar with CodeIgniter or ActiveRecord, so I can't speak to how that's made available.
Your code looks like it's using the PDO interface... but I'm not sure about that.
# either we need to check return from functions for errors
# or we can have PDO do the checks and throw an exception
$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
# attempt insert which will generate AUTO_INCREMENT value
$this->db->query("INSERT (ad_id, ... ) VALUES (NULL, ...)");
# if previous insert successfully inserted a row (or rows)
$ad_id = $this->db->lastInsertId();
You really need to check whether the previous insert was successful or not. If you aren't going to code that check yourself, then PDO does provide a mechanism that performs this checking automatically, and will throw an exception if a MySQL error occurs.
I've avoided copying your original code, which looks like it's vulnerable to SQL Injection. If you're using PDO, you can make effective use of prepared statements with bind placeholders, rather than including values in the SQL text.
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.
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.