Insert data into 2 tables using first table ID - php

I've two tables in my joomla 2.5 site component that trying to inset two tables and first table ID should be second table foreign-key.
Table: MYTABLE
-------------------------------------------------------------
| mytab_id | mytab_name | mytab_country | mytab_city |
-------------------------------------------------------------
Table: YOURTABLE
-------------------------------
| yourtab_id | group_name |
-------------------------------
mytab_id is auto increment value and that should insert to second table yourtab_id as foreign-key.
How should I insert data to both tables as first table id value to second table id.
I've tried below code but it doesn't work.
$insert_query = "INSERT INTO #__mytable (mytab_name, mytab_country, mytab_city) VALUES ('". $mytab_name."',".$mytab_country.",'".$mytab_city."'); ";
$db->setQuery( $insert_query );
$db->query();
$insert_query2 = "INSERT INTO #__yourtable (yourtab_id, group_name) VALUES (".LAST_INSERT_ID().", 2);";
$db->setQuery( $insert_query2 );
$db->query();
Thanks,

Try This,
In Joomla you can get the last insert id using
$db->insertid();
For details about Joomla DB Queries, Also try to use more standards in your query.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Insert columns.
$columns = array('mytab_name', 'mytab_country', 'mytab_city');
// Insert values.
$values = array($db->quote($mytab_name), $db->quote($mytab_country), $db->quote($mytab_city));
// Prepare the insert query.
$query
->insert($db->quoteName('#__mytable'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->query();
You can make your query standards like here
Hope it helps..

You can use the available php function to achieve this
mysql_insert_id()
you can refer Here For Documentation in php

Related

Insert an auto increment id to another column in same table and prepend a character without updating it on seperate query

Hello I need to insert the auto incremented 'invoice_id' to the second column 'invoice_code' and prepend the character 'z' to it. Is there a way to do it without updating it on seperate query?
Here's what i expect to see in my columns:
---------------------------------------------
| invoice_id | invoice_code | invoice_value |
---------------------------------------------
| 1| z1| sample value1 |
| 2| z2| sample value2 |
| 3| z3| sample value3 |
---------------------------------------------
Here's my query so far:
$query = "INSERT INTO invoices () VALUES(null,
'z'.invoice_id,
'sample value'.invoice_id
)";
You could do that by using mysqli's function mysqli_insert_id($conn)
$connection = new mysqli('localhost', 'root', 'root', 'database');
$query = "INSERT INTO invoices (invoice_value) VALUES('sample')";
// Creates new record
mysqli_query($connection, $query);
Then fetch last inserted id
// Fetches newly inserted id
$id = mysqli_insert_id($connection);
Then update the existing row
$update = "UPDATE invoices SET invoice_code='z".$id."' WHERE invoice_id = ". $id;
// Updates the existing record with autoincrement id
mysqli_query($connection, $update);
You need to know what is the next auto increment id for this table.
I will do this
$query = "SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = 'table_name' AND table_schema = DATABASE( )";
try something like,
$count = 1;
while ($count <= 3) {
$query .= "INSERT INTO invoices ("invoice_code", "invoice_value") VALUES('z'.$count, 'sample value'.$count);";
$count++;
}
Sorry edited, wasn't thinking.

INSERT INTO two different tables, but have the same ID?

I have a database of Users and another table for Teachers. Teachers have all the properties as a user but also an e-mail address. When inserting into the DB how can I insert the info, ensuring that the ID is the same for both?
the ID currently is on automatic incrament.
this is what I have at the moment:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$sqlQuery = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result=mysql_query($sqlQuery);
thank you!
use MYSQL function LAST_INSERT_ID()
OR php mysql http://ro1.php.net/manual/en/function.mysql-insert-id.php
why to use separate table for teachers. instead, you can have email field with in user table and additional field with flag (T ( for teacher) and U (for user). Default can be a U. This have following Pros.
Will Not increase table size as email would be varchar
Remove extra overhead of maintaining two tables.
Same Id can be used
If you want to have that as separate table then answer you selected is good one but make sure last insert id is called in same connection call.
After the first insert, fetch the last inserted id:
$last_id = mysqli_insert_id(); // or mysql_insert_id() if you're using old code
Or you could expand your second query and use mysql's integrated LAST_INSERT_ID() function:
$sqlQuery = "INSERT INTO teacher(id, email) VALUES ((SELECT LAST_INSERT_ID()), '$myEmail')";
Try this:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$id = mysql_insert_id();
$sqlQuery = "INSERT INTO teacher(id, email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
Insert data into two tables & using the same ID
First method
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($conn, $sqlQuery1);
$lastID = mysqli_insert_id($conn);
$sqlQuery2 = "INSERT INTO teacher(email, lastID) VALUES ('$myEmail', 'lastID')";
$result2 = mysqli_query($conn, $sqlQuery2);
If the first method not work then this is the second method for you
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($sqlQuery1);
$sqlQuery2 = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result2 = mysqli_query($sqlQuery2);
You can set the Foreign Key in your database table (phpMyAdmin/ MySQL Workbench) to let the Foreign Key follow the Primary Key (ID). Then the data after insert will auto-follow the Primary Key ID.
Example here,
Teachers table set ID - Primary Key
Users table set UserID - Foreign Key (will follow the Teachers table ID)
if you're using MySQL WorkBench, you can refer to this link to set a foreign key.
https://dev.mysql.com/doc/workbench/en/wb-table-editor-foreign-keys-tab.html
Hope I can help any of you.
Though you can use the LAST_INSERT_ID() function in order to get the last insert id, the best approach in this case is to create a column reference to user id table.
teacher
id | user_id | email
So the teacher.id could be anyting, but the user_id column is the real reference to user table.
If you use InnoDB table, you can make the database consistent using Foreign keys
You Should Use A Transaction In MySQL. First insert In One Table And GET LAST_INSERT_ID().
Insert LAST_INSERT_ID() In Second Table.
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$sqlQuery = "INSERT INTO teacher(LAST_INSERT_ID(), email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);

SQL - Inserting data where values are an array

I want to be able to add an array of strings to a table so that each string is a new row (in PHP).
This is it in psuedo-code:
$Array = "10000,10001,10002,10003";
$Data = "ImportantData";
mysqli_query($db, "INSERT INTO MyTable(`id`,`data`) VALUES($Array, $Data)");
So that a previously empty table would look like:
id | data
------------------------
10000 | ImportantData
10001 | ImportantData
10002 | ImportantData
10003 | ImportantData
In an update script, with those rows already established, I could just say:
mysqli_query($db, "UPDATE MyTable SET data = $Data WHERE `id` IN($Array));
However I want it to create rows, not just update old ones.
Is there any way I can do this?
Just create a foreach loop on $Array, and insert the data. I assume you want to update it if it exists as it makes little sense to create a new record with the same PK, so use the following (assumes you are using PHP PDO
INSERT INTO MyTable (id,data) VALUES (:id,:data) ON DUPLICATE KEY UPDATE data=:data;
Use REPLACE INTO:
REPLACE INTO table SET id = 10001, data = 'new important data';
MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/replace.html

Insert data into different tabels

I´m trying to insert data into diferent tabels with php, but dosent get it to work.
Heres my db structure: 1
Table: event
Structure: FromDate | ToDate | locationID
Heres my db structure: 2
Table: jointable
Structure: EventID | locationID
The thing i want to do more specific, i have inputs for "Fromdate" and "todate" and "locationid". I want to input fromdate and todate into table1, and locaionid to table2
Here is my sql query:
mysql_query("INSERT INTO event (FromDate, ToDate, locationID)
VALUES ('$_POST[startdate]','$_POST[enddate]','$_POST[locationID)");
Any idea how i can "sort out" locationID to input it on my jointable instead?
Excuse for my bad enlish, i hope you understand what im trying to do.
Try this:
mysql_query("INSERT INTO `events` VALUES('".$_POST["startdate"]."','".$_POST["enddate"]."','".$_POST["locationID"]."')");
Call another query for inserting into other table:
mysql_query("INSERT INTO `jointable` VALUES('','".$_POST["locationID"]."')");
Write 2 different queries
Something Like This :
$startDate = $_POST[start_date];
$endDate = $_POST[to_date]
$locationId = $_POST[location_id];
mysql_query("INSERT INTO event VALUES ('$startDate','$endDate','$locationId");
mysql_query("INSERT INTO jointable VALUES ('','$locationId')");
Note : mysqL_* functions are being depreciated . Avoid the,

Add Prefix to auto-increment in mysql db

I have my database with table test1.
It has a primary id "Id" which is auto-increment.
Now the id is in the format 1,2,3.. . .Is it possible to store the primary Id as
PNR1,PNR2,PNR3 .. . . and so on(with auto-increment).
No. Either add the prefix in the query, or use a view instead.
Not really, but you can use another column (but a view)
this is already covered here:
MySQL Auto Increment Custom Values
Yes you can do it if you have INT prefix. You have id as INT in table
// START PREFIX
$query = mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 1");
// GET THE LAST ID MAKE SURE IN TABLE YOU 9991
while ($row = mysql_fetch_object($query)) {
$lastId = $row->id;
}
list($prefix,$Id) = explode('999',$lastId );
$Id = ($Id+1);
$new_id = '999'.$Id;
// END PREFIX
$insertQuery = mysql_query("INSERT INTO `table_name` SET id = '".$new_id."',...");
Hi, I made it work in this way :
Products Table (products):
id_prod(varchar(11), NOT NULL, PK), name(varchar(40))
Products Sequence Table (productidseq):
id(AI, PK, NOT NULL)
Before Insert Trigger in Products Table:
CREATE DEFINER=`root`#`localhost` TRIGGER `dbname`.`products_BEFORE_INSERT` BEFORE INSERT ON `products` FOR EACH ROW
BEGIN
insert into productidseq (id) values(NULL);
set new.id_prod = concat('PROD or any prefix here',last_insert_id());
set #productId = new.id_prod; -- To use outside of trigger this variable is useful.
END
When you run below query :
insert into products (name) values('Bat');
data inside tables will we be like this :
products:
id | name
---|-----
1 | Bat
productidseq:
id
---
1
If any better way than this or any cons with this, please comment below. Thanks.

Categories