Page 1 of 1

Help with inserting data into the tables (Im new to php).

Posted: Wed Nov 24, 2010 10:21 am
by atom
Lets say I have this database:

table brand [brandID] [brandName] where brandID -> auto increment and one brand always has the same brandID
table product [brandID] [productID] [price] where productID -> auto increment

I want to insert new product into the database using only values [brandName] and [price]
and want brandID and productID to be created automatically


I use this form:

<form id="insertingDataToBrand" action="administratorCode.php" method="post">
<div>Brand Name: <input type="text" name="brandName"/></div>
<div>Price: <input type="text" name="price"/></div>
</form>

And here is the php code:

<?php
//connection to database
include 'connectToDatabase.php';

//data retrieveing
$brand = $_POST['brandName'];
$price = $_POST['price'];

//As I am inserting to two different tables I use two INSERT statements
$sql = "INSERT INTO brand (brandName) values ('$brand')";

mysql_query($sql) or die (mysql_error());

//as brandID is created automatically I am going to insert the same value to another table
$last_id = mysql_insert_id ();

$sql = "INSERT INTO product (price, brandID) values ('$price', '$last_id')";

?>

This should work just fine (it doesnt tho) BUT my question is:

I have 3 different brands (brand A with brandID 1, brand B with brandID 2, brand C with brandID 3).
When want to insert brand D, automatically created brandID should be automatically set to 4. BUT
when I want to insert product of the same brand, lets say brand A (with different productID) brandID is automatically set to 4(or higher) as well.

What do I have to do(use) so it would be able to realise what brandID should be added?

Thanks a lot.

Re: Help with inserting data into the tables (Im new to php)

Posted: Fri Nov 26, 2010 12:46 am
by rahulzatakia
Hi, please use the following code and let me if its fine with you or not.

<form id="insertingDataToBrand" action="administratorCode.php" method="post">
<div>Brand Name: <input type="text" name="brandName"/></div>
<div>Price: <input type="text" name="price"/>
<label>
<input type="submit" name="Submit" value="Submit">
</label>
</div>
</form>

And here is the php code:

<?php
if(isset($_POST['brandName'])) {
//connection to database
include 'connectToDatabase.php';

//data retrieveing
$brand = $_POST['brandName'];
$price = $_POST['price'];

//As I am inserting to two different tables I use two INSERT statements
$sql = "INSERT INTO brand (brandName) values ('$brand')";

mysql_query($sql) or die (mysql_error());

//as brandID is created automatically I am going to insert the same value to another table
$last_id = mysql_insert_id ();

$sql = mysql_query("INSERT INTO product (price, brandID) values ('$price', '$last_id')");

}
?>