Inserting problem

Hi, I have problem in inserting,is it possible to insert in more than one table?

for example i have a form with 3 fields now when i am going to submit this form,the 3 fields will be inserted into three different table…


firstname “jemz”====>will be inserted to first table
middlename “chan”====>will be inserted to second table
lastname “gimz”=====>will be inserted to third table

I don’t know how to do it in php code,can you please help me.

Thank you in advance.

You can… But why on earth would you store something such as fname, mname and lname on different tables?!

//define yoru variables
$first_name = 'Kyle';
$last_name = 'Wolfe';

//establish a connection
$dbh = new PDO('mysql:host=localhost;dbname=test', "user", "pass");

//query 1
$stmt = $dbh->prepare ("INSERT INTO tbl_table1 (first_name) VALUES (:first_name)");
$stmt -> bindParam(':first_name, $first_name);
$stmt -> execute();

//query 2
$stmt = $dbh->prepare ("INSERT INTO tbl_table2 (last_name) VALUES (:last_name)");
$stmt -> bindParam(':last_name, $last_name);
$stmt -> execute();

//close connection
$stmt -> close();

Yes Jemz,

This sounds like it could be a poor DB choice. Can you let us know how the name data will be used. Incidentally, name data is normally set in one table; say identies, users … For example to join usernames with other DB data, one typically uses JOINS in there Database calls to query multiple tables and join the information into on tablature set.

Hi servertstorm and wolf, thank you for the reply…

You can… But why on earth would you store something such as fname, mname and lname on different tables?!

it is just an example for me…i just want to know on how to insert in 3 different tables in just one click of the button…:slight_smile:

Hi wolf, so you are trying to say that in my one php file i have 2 insert statement:

please correct me if i am wrong.

    type: 'post',
    data: 'fname='+first+'&lname='+last,
    url: 'toMystudent.php'
    success: function(result)

      alert('successfully save');



 include_once 'mydbconnection.php';

       $first = $_post['fname'];
       $last = $_post['lname'];
       $sql = mysql_query("insert into`firstnametable` (firstname) values('$first')");

      $sql = mysql_query("insert into`lastnametable` (lastname) values('$last')");



At a glance it looks good, but please use PDO as the example I provided to prevent SQL Injection, which yours would currently allow.

Hi wolfe…is it okay, that i will change some part of my code to PDO ?does my php file will still run?

example in my insert statement i will change it to PDO statement like what you did.but some part of my program will still be not PDO…

Using PDO will allow your php file to run. Just try it, and you will see.

Hi serverstorm, Even my connection to the database is not a PDO?:slight_smile: