How to insert data into two relational tables?
Let’s we have created two table in sms databases as follows:
Table 1: product _category with sample records
Id |
name |
1 |
Mobile |
2 |
computer |
Table 2: product with sample records
Id |
name |
price |
category_id |
1 |
nokia C2 |
6000 |
1 |
2 |
processor |
4000 |
2 |
SQL for the above tables.
File name: my_db.sql
DROP DATABASE IF EXISTS `sms`;
DROP DATABASE IF EXISTS `sms`;
create database sms;
use sms;
DROP TABLE IF EXISTS `product_category`;
CREATE TABLE `product_category`(
`id` int(10) unsigned NOT NULL primary key auto_increment,
`name` varchar(50) default NULL
) ENGINE=MyISAM;
DROP TABLE IF EXISTS `product`;
CREATE TABLE`product`(
`id` int(10) unsigned NOT NULL primary key auto_increment,
`name` varchar(50) default NULL,
`price` int(10) default NULL,
`category_id` int(10) default NULL
) ENGINE=MyISAM;
Interface Design:
HTML code for above user interface
File name: demo.htm
<form action="save.php" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="txtName" /></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" name="txtPrice" /></td>
</tr>
<tr>
<td>Category</td>
<td><input type="text" name="txtCategory" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" name="btnSubmit"/></td>
</tr>
</table>
</form>
PHP Code:
File name: save.php
<?php
if (isset($_POST["btnSubmit"])){
$name=$_POST["txtName"];
$price=$_POST["txtPrice"];
$category=$_POST["txtCategory"];
$db=new mysqli("localhost","root","****","Your DB");
$db->query("insert into product_category(name)values('$category')");
$last_id=$db->insert_id;
$db->query("insert into product(name,price,category_id)values('$name','$price','$last_id')");
}
?>
Comments 5