Inserting data into multiple MySQL tables using PHP

They have: 20 posts

Joined: Dec 2008

I am new to PHP. What I would like to do is insert data from an HTML form using PHP and inserting the data into multiple tables in MySQL.

The following code only inputs data into one table. When I click Submit and all the fields in the form have been filled out the data is saved in the database, but if 1 field is left out the whole form is not recorded in the database, why?

I would like to insert data into multiple tables. I have hit a road block and I cannot move forward.

<?php
  
        $self
= $_SERVER['PHP_SELF'];
           
$name = $_POST['name'];
       
$street = $_POST['street'];
       
$city = $_POST['city'];
       
$zip = $_POST['zip'];
       
$state = $_POST['state'];
       
$country = $_POST['country'];
       
$telephone = $_POST['tel'];
       
$fax = $_POST['fax'];
       
$website = $_POST['www'];
?>

Casino Name:
Street address:
City:
Zip:
State:
Country:
Telephone:
Fax:
Website:

 

<?php
if($name and $street and $city and $zip and $state and $country and $telephone and $fax and $website ) //ensure value exist
   
{ // connect to mysql
   
$conn = @mysql_connect("localhost", "user", "password")
            or die(
"ERR: Connection");
           
    
// select specified database
    
$rs = @mysql_select_db("casino_list", $conn)
             or die (
"ERR: DB");
           
    
// create query
    
$sql = "insert into casino_tbl (id, name, street, city, zip, state, country, telephone, fax, website)
         values ('', '"
.$name."', '".$street."', '".$city."', '".$zip."', '".$state."', '".$country."','".$telephone."', '".$fax."', '".$website."')";
   
    
// execute query
    
$rs = mysql_query($sql, $conn);
    
    
// confirm the added record details
    
if($rs){echo("Record added: $name $street $city $zip $state $country $telephone $fax $website");}
     }
?>

Thank you

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

The following code only inputs data into one table. When I click Submit and all the fields in the form have been filled out the data is saved in the database, but if 1 field is left out the whole form is not recorded in the database, why?

It's because of this statement that checks the values before continuing:

if($name and $street and $city and $zip and $state and $country and $telephone and $fax and $website ) //ensure value exist

I would like to insert data into multiple tables. I have hit a road block and I cannot move forward.

If you want to enter the data in multiple tables, then you need to duplicate this line:

     // create query
     $sql = "insert into casino_tbl (id, name, street, city, zip, state, country, telephone, fax, website)
         values ('', '".$name."', '".$street."', '".$city."', '".$zip."', '".$state."', '".$country."','".$telephone."', '".$fax."', '".$website."')";

Replace casino_tbl with the other table you want to insert the data into.

Also, I should note that you should be escaping your data before inserting any data into your database. That first block of code you posted should be something like:

<?php
 
        $self
= $_SERVER['PHP_SELF'];
       
$name = mysql_real_escape_string($_POST['name']);
       
$street = mysql_real_escape_string($_POST['street']);
       
$city = mysql_real_escape_string($_POST['city']);
       
$zip = mysql_real_escape_string($_POST['zip']);
       
$state = mysql_real_escape_string($_POST['state']);
       
$country = mysql_real_escape_string($_POST['country']);
       
$telephone = mysql_real_escape_string($_POST['tel']);
       
$fax = mysql_real_escape_string($_POST['fax']);
       
$website = mysql_real_escape_string($_POST['www']);
?>

Welcome to the forums. Smiling

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Just another couple of notes.. As I cannot see your entire code and you may have only posted rough examples of what you have, this may be obsolete advice...but...

the problem with using or die("ERR: Connection"); in a mysql connect or table select code is it outputs a message to the screen and the script halts.
You shouldn't be using this in a public environment. Instead, a friendlier situation, you already use an @ before the code to stop any error outputting, so the next step is an error message you create from there being no data returned
EG - (taken from your code)

<?php
// execute query
$rs = mysql_query($sql, $conn);
   
// confirm the added record details
if($rs){
echo(
"Record added: $name $street $city $zip $state $country $telephone $fax $website");
}else{
echo
"data could not be inserted, sorry, please try again blah etc";
}
?>

Or of course on mysql insert you can use mysql_affected_rows($rs), which returns a numerical value of the number of rows "affected" i.e. inserted, into a mysql table
Just make sure you check for 0 or less than 0 ('<=0') as sometimes mysql returns -1 (minus one) for no rows found/inserted.

And just adding to pr0gr4mm3rs good advice .. you need a mysql connection before using mysql_real_escape_string, so take that into account within your code, as currently your vars are set before your connection to the DB is done

So you need this

<?php
// connect to mysql
$conn = @mysql_connect("localhost", "user", "password")
or die(
"ERR: Connection");
?>

before this
<?php
$variable
= mysql_real_escape_string($variable);
?>

Also you don't have an else for this

<?php
if($name and $street and $city and $zip and $state and $country and $telephone and $fax and $website ) //ensure value exist
?>

so if those vars are not set, nothing will happen unless there is code underneath the } of the if
EG
<?php
}else{
echo
"sorry, not all vars where set, please go back and input ALL fields";
}
?>

Or, send them back to the form page and tell them they didn't insert all fields

They have: 20 posts

Joined: Dec 2008

I have tried to have this data posted on the database and it just wont go. I dont understand this at all?

The first table data gets posted but the rest dont. How could I improve this code.

<?php
  
        $self
= $_SERVER['PHP_SELF'];
       
$hotel_name = $_POST['hotel_name'];
       
$street = $_POST['street'];
       
$city = $_POST['city'];
       
$zip = $_POST['zip'];
       
$state = $_POST['state'];
       
$country = $_POST['country'];
       
$telephone = $_POST['tel'];
       
$fax = $_POST['fax'];
       
$website = $_POST['www'];
       
$rest_name = $_POST['rest'];
       
$roulette = $_POST['roulette'];
       
$bj = $_POST['bj'];
       
$punto_banco = $_POST['punto'];
       
$poker = $_POST['poker'];
       
$three_card_poker = $_POST['tcp'];
       
$spanish = $_POST['spanish'];
       
$craps = $_POST['craps'];
       
$card_room = $_POST['card'];
       
$slots = $_POST['slots'];
?>

Casino Name:
Street address:
City:
Zip:
State:
Country:
Telephone:
Fax:
Website:

Restuarants:

Casino Games (enter number of tables)
Slots:
Roulette:
BJ:
Punto Banco:
Poker:
Three Card Poker:
Spanish 21:
Craps:
Card Room:

 

<?php
    
// connect to mysql
   
$conn = @mysql_connect("localhost", "username", "password")
            or die(
"ERR: Conn");
           
    
// select specified database
    
$rs = @mysql_select_db("casino_list", $conn)
             or die (
"ERR: DB");
           
   
    
// create query
    
$sql = "insert into casino_tbl (id, hotel_name, street, city, zip, state, country, telephone, fax, website)
              values ('', '"
.$hotel_name."', '".$street."', '".$city."', '".$zip."', '".$state."', '".$country."','".$telephone."', '".$fax."', '".$website."')";
   
   
// execute query
    
$rs = mysql_query($sql, $conn);
        
    
$sql = "insert into restaurant_tbl (id, hotel_name, rest_name)
             values('', '"
.$hotel_name."', '".$rest_name."')";   
   
// execute query
    
$rs = mysql_query($sql, $conn);
    
    
$sql = "insert into games_tbl (id, hotel_name, roulette, bj, punto-banco, poker, three-card-poker, spanish, craps, card-room)
             values('', '"
.$hotel_name."', '".$slots."', '".$roulette."', '".$bj."', '".$punto_banco."','".$poker."', '".$three_card_poker."', '".$spanish."', '".$craps."', '".$card_room."',)";
   
    
// execute query
    
$rs = mysql_query($sql, $conn);
    
    
// confirm the added record details
    
if($rs){echo("Record added: $hotel_name");}
    
?>

Thanks

They have: 1 posts

Joined: Jul 2010

hello gentlemen,
I am experiencing the same problem, I am trying to create an application with multiple tables for my business that unfortunately is not doing that well and unfortunately I do not have the funds to support a programmer. I have some and less than basic php knowledge but quite a good understanding of mysql. My problem is that I am trying to insert data into different tables for keeping better record of my customers, employees and so on. What I did is that I created a table called users in mysql, also I created another table called user_addresses for giving the users the ability to add multiple addresses. What I did in order to identify what user has what address is that I pretty much created a second Id that is connected with the table of users which means, if the "users" table has a primary id called "ut_id" and every user gets assigned with an automated id then on the table user_addresses I added the same ID after the primary key id of the user addresses table. Then every time I add a record to the table user addresses I can assign a user. The question is how can I make the php script to do that automatically. ie. if a user fills up the form, obviously there will be fields that will add the data on the table "2" which is for the addresses. How can I make the script to get that ID from the table one and add it to the table 2 as well so the data will be assigned to that user automatically? I am really sorry if I am bothering with that question but I really need your help here Smiling Thank you so much in advance though.

He has: 53 posts

Joined: Jun 2010

Hi, Still I have no Idea about that, But I am Sure that, I'll Solve your Problem as soon as possible.

They have: 2 posts

Joined: Mar 2011

In general, here's how you post data from one form into two tables:

<?php
$dbhost
="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";

$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());

$mysql_select_db($dbname, $con);

$sql="INSERT INTO table1 (table1id, columnA, columnB)
         VALUES (' ', '
$_POST[columnA value]','$_POST[columnB value]')";

mysql_query($sql);

$lastid=mysql_insert_id();

$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
             
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";

//tableid1 & tableid2 are auto-incrementing primary keys

mysql_query(
$sql2);

mysql_close(
$con);
?>

//this example shows how to insert data from a form into multiples tables, I have not shown any security measures

They have: 2 posts

Joined: Mar 2011

Not sure if this got through the first time I posted it. In general, here's how you post data from one form into two tables (action script):

<?php
$dbhost
="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";

$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());

$mysql_select_db($dbname, $con);

$sql="INSERT INTO table1 (table1id, columnA, columnB)
         VALUES (' ', '
$_POST[columnA value]','$_POST[columnB value]')";

mysql_query($sql);

$lastid=mysql_insert_id();

$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
             
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";

//tableid1 & tableid2 are auto-incrementing primary keys

mysql_query(
$sql2);

mysql_close(
$con);
?>

//this example shows how to insert data from a form into multiples tables, I have not shown any security measures

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.