0

I have two mysql tables

Table1 : Columns (id(int pk), empid(int), status( varchar(1) ) )
Table2 : Columns (idfk(int fk), paycodeidfk(int fk), amount(int) )

Relation : Table1->id is Primary Key and Table2->idfk is Foreign Key

How could i insert rows at same time in both relational tables using PDO.

0

2 Answers 2

0

for php code

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// First Query
$stmt = $conn->prepare("INSERT INTO `Table1` (`id`, `empid`, `status`) VALUES (?,?,?)";
$stmt->execute([0, 11, 0]);

// Get lastInsrtId
$last_id = $conn->lastInsertId();

// Second Query
$stmt = $conn->prepare("INSERT INTO `Table2` (`idfk`, `paycodeidfk`, `amount`) VALUES (?,?,?);";
$stmt->execute([$last_id, 22, 99]);
Sign up to request clarification or add additional context in comments.

3 Comments

How could i use LAST_INSERT_ID in second insert query : INSERT INTO Table2 (idfk, paycodeidfk, amount) VALUES (0, 22, 99);
Dear please focus my question, i want to insert these two rows at a same time..... with single function call.
Like : sqlqry = ' INSERT INTO Table1 (id, empid, status) VALUES ('', 11, 0); INSERT INTO Table2 (idfk, paycodeidfk, amount) VALUES (lastinserid(), 22, 99); ' I want to execute both insert quires at same time with one function call.
-1

If you want to save with on query you can do as follows:

INSERT INTO Table1 (empid, status) VALUES (1,2)
INSERT INTO Table2 (paycodeidfk, amount) VALUES(LAST_INSERT_ID(), 345)

In addition you can just use this query with with PhP PDO class(add paran key instead of value items).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.