Insert a value into multiple tables - php

Okay, I am trying to submit values from a php form into multiple tables. My php code is working fine but values such as patientID are inserting into "patients" for example: PatientID; 100 fine but the same value for PatientID is not inserting the same unique value into another table for example: the "Disease" table. Am I doing something wrong?
**revised question
I'm not sure if I have the relationships between the tables correctly assigned. Here are the tables and the relationships between them.
Patient Attends Accident & Emergency
Patient seen_by Nurse
Nurse assesses disease of patient
{{nurse assigns priority to patient}} Priority linked to patient and nurse
{{nurse gives patient waiting time}} Time linked to nurse and patient
{{doctor will see patient based on their waiting time and priority}} Doctor linked to both time and priority.
Accident & Emergency; (ID(PK), PatientID(FK) Address, City, Postcode, Telephone)
Patient (ID(PK), Forename, Surname, Gender, Dateofbirth, Address, Patienthistory, illness,
Nurse(ID(PK) Forename, surname)
Assesses(ID(PK)NurseID(FK), PatientID(FK))
Disease(ID(PK), illness, symptoms, diagnosis, treatment) {{nurse assesses disease of patient (these tables should all be linked}}
Priority (ID, NurseID(FK), PatientID(FK), DoctorID(FK), Priority)
Time(ID,NurseID, PatientID, DoctorID, Arrival Time, Expected waiting time, Discharge time)
Doctor (ID,Firstname, Surname)
Revised PHP code. ID is not inserting into tables; for example: PatientID is not inserting into the Disease table.
<?php
$con = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
//get NURSE values from form
$nurse_ID = $_POST['nurse_ID'];
$nurse_name = $_POST['nurse_name'];
$nurse_lastname = $_POST['nurse_lastname'];
//get Disease values from form
$disease_ID = $_POST['disease_ID'];
$symptoms = $_POST['symptoms'];
$diagnosis = $_POST['diagnosis'];
$treatment = $_POST['treatment'];
//get Patient values from form
$patient_id = $_POST['patient_id'];
$patient_name = $_POST['patient_name'];
$patient_lastname = $_POST['patient_lastname'];
$gender = $_POST['gender'];
$dateOfBirth = $_POST['dateOfBirth'];
$monthOfBirth = $_POST['monthOfBirth'];
$yearOfBirth = $_POST['yearOfBirth'];
$address = $_POST['address'];
$history = $_POST['history'];
$illness = $_POST['illness'];
$priority = $_POST['priority'];
$priority_id = $_POST['priority_id'];
// Validate
$date = $dateOfBirth.'-'.$monthOfBirth.'-'.$yearOfBirth;
$sql ="INSERT INTO Nurse(Forename, Surname)
VALUES('$nurse_name', '$nurse_lastname')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
echo "$nurse_ID"; mysql_insert_id(); //get the assigned id for a nurse
$sql ="INSERT INTO Disease(Illness, Symptoms, Diagnosis, Treatment, PatientID)
VALUES('$illness', '$symptoms', '$diagnosis', '$treatment', '$patient_id')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
echo "$patient_id"; mysql_insert_id(); //get the assigned id for a patient
//use nurse_id and patient_id
$sql ="INSERT INTO Priority(NurseID, PatientID, Priority)
VALUES('$nurse_ID', '$patient_id', '$priority')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
echo "$priority_id"; mysql_insert_id(); //get the assigned id for priority
echo "$patient_id"; mysql_insert_id(); //get the assigned id for a patient
$sql="INSERT INTO Patient(Forename, Surname, Gender, Date_Of_Birth, Address, Patient_History, Illness, Priority)
VALUES ('$patient_name', '$patient_lastname', '$gender', '$date', '$address', '$history', '$illness', '$priority')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
echo "$patient_id"; mysql_insert_id(); //get the assigned id for a patient
echo "1 record added";
// close connection
mysql_close($con);
?>

you need to use unique ids, names and lastname for different entities (nurse, patient, disease etc). And then use them appropriately in INSERT statements. See revised code below.
select your db only once at the beginning of the script with mysql_select_db (if you planning to stick with mysql_*).
Sanitize and validate input from the user before inserting it.
Insert your records in correct (logical) order (nurse, patient, disease, priority).
Now all of your ids come via POST. You might consider using id auto-reneration in mysql.
You have a missing variable $priority_id. I've put it in the revised code assuming that you get it the same way via POST.
Do proper error handling not just die().
Better consider to switch to PDO or mysqli_* and use prepared statements.
Revised code (updated):
Assumption is that auto_increment is enabled for the id column of every table.
$con = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
mysql_select_db("a&e", $con) or or die('Could not select database.');
//get NURSE values from form
//We don't need to post an id for a Nurse since mysql will assign it for us
//$nurse_id = $_POST['nurse_id'];
$nurse_name = $_POST['nurse_name'];
$nurse_lastname = $_POST['nurse_lastname'];
//get Disease values from form
// We don't need to post an id for a Disease since mysql will assign it for us
//$disease_id = $_POST['disease_id'];
$symptoms = $_POST['symptoms'];
$diagnosis = $_POST['diagnosis'];
$treatment = $_POST['treatment'];
//get Patient values from form
//We don't need to post an id for a Patient since mysql will assign it for us
//$patient_id = $_POST['patient_id'];
$patient_name = $_POST['patient_name'];
$patient_lastname = $_POST['patient_lastname'];
$gender = $_POST['gender'];
$dateOfBirth = $_POST['dateOfBirth'];
$monthOfBirth = $_POST['monthOfBirth'];
$yearOfBirth = $_POST['yearOfBirth'];
$address = $_POST['address'];
$history = $_POST['history'];
$illness = $_POST['illness'];
$priority = $_POST['priority'];
//We don't need to post an id for a Priority entity since mysql will assign it for us
//missing variable
//$priority_id = $_POST['priority_id'];
//Sanitize and validate your input here
// ...skipped
// Validate
$date = $dateOfBirth.'-'.$monthOfBirth.'-'.$yearOfBirth;
//We don't provide an id for a Nurse since mysql will assign it for us
$sql ="INSERT INTO Nurse(Forename, Surname)
VALUES('$nurse_name', '$nurse_lastname')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
$nurse_id = mysql_insert_id(); //get the assigned id for a nurse
//We don't provide an id for a Patient since mysql will assign it for us
$sql="INSERT INTO Patient(Forename, Surname, Gender, Date_Of_Birth, Address, Patient_History, Illness, Priority)
VALUES('$patient_name', '$patient_lastname', '$gender', '$date', '$address', '$history', '$illness', '$priority')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
$patient_id = mysql_insert_id(); //get the assigned id for a patient
//We don't provide an id for a Disease since mysql will assign it for us
$sql ="INSERT INTO Disease(Illness, Symptoms, Diagnosis, Treatment, PatientID)
VALUES('$illness', '$symptoms', '$diagnosis', '$treatment', '$patient_id')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
//We don't provide an id for a Priority since mysql will assign it for us
//But we use $nurse_id and $patient_id that we get earlier
$sql ="INSERT INTO Priority(NurseID, PatientID, Priority)
VALUES('$nurse_id', '$patient_id', '$priority')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
echo "1 record added";
// close connection
mysql_close($con);

While I don't entirely understand how your system is supposed to work, you can see in the following code that it will never insert different IDs for the disease ID and the patient ID:
$sql ="INSERT INTO Disease(ID, Illness, Symptoms, Diagnosis, Treatment, PatientID)
VALUES('$id', '$illness', '$symptoms', '$diagnosis', '$treatment', '$id')";
Basically you're inserting a disease ID which is exactly the same as the patient ID. You probably want to have different variables for those.
Regarding my comment above:
You can filter like this:
$id = intval($_POST['ID']);
$name = filter_input(INPUT_GET | INPUT_POST, $_POST['name']); // works in PHP 5.2.x and above
Regarding MySQL, see this post:
Why shouldn't I use mysql_* functions in PHP?

Related

PHP/MYSQL Selecting a MAX value and using it as an inserted value

I have a small database project using HTML forms and PHP code. It is working perfectly except the last part. Basically, I have my database connection setup and working in my PHP, and upon hitting the Add button it should insert values from the form to the database. My instructor said that due to table constraints it has to be inserted in a certain order, basically address table first and then staff table. IF I comment out the staff part of code, my successful confirmation page appears and the address appears in the database every time with an auto incremented address_id. The issue is that I'm supposed to query for a MAX(Address_id) and use that for inserting the staff part, as it uses address_id as a foreign key. When I do that, I get a foreign key constraint error on update cascade. If I completely pull out the INSERT staff code, and put a 'debug' to print the MAX(address_id), it prints correctly. I just can't get it to insert to the staff table correctly so that everything from my form creates a staff record. Here is the code:
$userQuery = "INSERT INTO address (address, district, city_id, postal_code, phone)
VALUES ('$address', '$district', '$city', '$postal_code', '$phone') ";
$addressResult = mysqli_query($connect, $userQuery);
if (!$addressResult)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
$maxQuery = "SELECT MAX(address_id) FROM address";
$result = mysqli_query($connect, $maxQuery);
$row = mysqli_fetch_assoc($result);
if (!$result)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
/**else
{
print ("<p>Average hourly wage:".$row['MAX(address_id)']."</p>");
}**/
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id)
VALUES ('$first_name', '$last_name', '$row', '$email', '$store_id')";
$staffResult = mysqli_query($connect, $userQuery1);
if (!$staffResult)
{
die("Could not successfully run query ($userQuery1) from $db: " .
mysqli_error($connect) );
}
else
{
print(" <h1>New Staff Record Added!</h1>");
print ("<p>The following record was added:</p>");
print("<table border='0'>
<tr><td>First Name</td><td>$first_name</td></tr>
<tr><td>Last Name</td><td>$last_name</td></tr>
<tr><td>Email</td><td>$email</td></tr>
<tr><td>Store ID</td><td>$store_id</td></tr>
<tr><td>Address</td><td>$address</td></tr>
<tr><td>City</td><td>$city</td></tr>
<tr><td>District</td><td>$district</td></tr>
<tr><td>Postal Code</td><td>$postal_code</td></tr>
<tr><td>Phone</td><td>$phone</td></tr>
</table>");
}
You are not calling the correct associative index. You are just calling the array:
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id) VALUES ('$first_name', '$last_name', '{$row['MAX(address_id)']}', '$email', '$store_id')";

PHP inserting into two tables from one form not working

Below is my php code, which should take the data from my form and put it into two tables in my database. However I keep getting an SQL syntax error by the values, I was originally putting the values in ' ' however I got the error so then I changed the values to backticks . But that still didnt seem to make much difference. Im receiving the error, however street, city, county, postcode, tel and date of birth are all inputting into the users table. But nothing else, and nothing is going into the members table.
Any help would be greatly appreciated. Many thanks
$con = mysql_connect("localhost", "alex", "");
if(!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("gym", $con);
//** code above connects to database
$sql ="INSERT INTO users (First_Name, Last_Name, Street, City, County, Postcode, Telephone, Email, Date_Of_Birth, Gender)
VALUES
(`$_POST[FirstName]`,
`$_POST[LastName]` ,
`$_POST[Street]`,
`$_POST[City]`,
`$_POST[County]`,
`$_POST[Postcode]`,
`$_POST[Tel]`,
`$_POST[Email]`,
`$_POST[Date_Of_Birth]`,
`$_POST[Gender]`)";
$result1=mysql_query($sql,$con);
$sql1 = "INSERT INTO members( Membership_Number, Membership_Type, Membership_Referal, Trainer_Required, Medical_Informaton, Contract, Card_Holder_Name, Bank, Card_Number, Sort_Code, valid, Exp, Security_Number
VALUES
(`$_POST[MembershipNumber]`,
`$_POST[MembershipType]`,
`$_POST[MembershipReferral]`,
`$_POST[TrainerRequired]`,
`$_POST[MedicalInformation]`,
`$_POST[Contract]`,
`$_POST[BankBranch]`,
`$_POST[CardHolderName]`,
`$_POST[CardNUMBER]`,
`$_POST[Expiry]`,
`$_POST[SecurityCode]`)";
$result2=mysql_query($sql1,$con);
//***** code below is error message if it doesnt work
if($result1 && $result2){
printf("window.alert(\"New Record Added!\");");
}
else
{
echo "Error:". mysql_error()."";
}
mysql_close($con)
?>​
Remove backtics and add `single quote` to values parameter
User SQL query like.
$sql = "INSERT INTO users (First_Name, Last_Name) VALUES('".$_POST[FirstName]."','".$_POST[LastName]."')";
You must pass parameter between {$_POST['variable']} like this:
$sql1 = "INSERT INTO members( Membership_Number, Membership_Type, Membership_Referal, Trainer_Required, Medical_Informaton, Contract, Card_Holder_Name, Bank, Card_Number, Sort_Code, valid, Exp, Security_Number
VALUES
(`{$_POST['MembershipNumber']}`,
`{$_POST['MembershipType']}`,
`{$_POST['MembershipReferral']}`,
`{$_POST['TrainerRequired']}`,
`{$_POST['MedicalInformation']}`,
`{$_POST['Contract']}`,
`{$_POST['BankBranch']}`,
`{$_POST['CardHolderName']}`,
`{$_POST['CardNUMBER']}`,
`{$_POST['Expiry']}`,
`{$_POST['SecurityCode']}`)";
please use ' not use `
just like
'$_POST[value]', ........, ........

Inserting into database with PHP not working

below is my php script to input data into my database from my form. You can see my form here... http://studentnet.kingston.ac.uk/~k1202101/workshop2/CreateNewAccount.html
I get an error message when I try to submit the form. The error message I get is
'Error:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name, Medical Information, First Name, Membership Type, D.O.B, Gender, Membershi' at line 1'
I have gone over my code but still cant see where I have gone wrong? Any help would be greatly appreciated.
<?php
define('DB_NAME', 'demo'); //**your database name
define('DB_USER','alex'); //**your user ID
//**your password
define('DB_HOST', 'localhost'); //**your local host or KU host
$link = mysql_connect(DB_HOST, DB_USER);
if(!$link)
{
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected)
{
die('Can\'t use'. DB_NAME . ':' . mysql_error());
}
$value1 = $_POST['Last Name'];
$value2 = $_POST['Medical Information'];
$value3 = $_POST['First Name'];
$value4 = $_POST['Membership Type'];
$value5 = $_POST['D.O.B'];
$value6 = $_POST['Gender'];
$value7 = $_POST['Membership Referral'];
$value8 = $_POST['Trainer Required'];
$value9 = $_POST['Membership Number'];
$value10 = $_POST['Contract'];
$value11 = $_POST['House Number/Street'];
$value12 = $_POST['City'];
$value13 = $_POST['County'];
$value14 = $_POST['Postcode'];
$value15 = $_POST['Tel'];
$value16 = $_POST['E-Mail'];
$value17 = $_POST['Bank Branch'];
$value18 = $_POST['Card Holder Name'];
$value19 = $_POST['Card Number'];
$value20 = $_POST['Security Code'];
$sql ="INSERT INTO test(Last Name, Medical Information, First Name, Membership Type, D.O.B, Gender, Membership Referral, Trainer Required, Membership Number , Contract, House Number/Street, City, County, Postcode, Tel, E-Mail, Bank Branch, Card Holder Name, Card Number, Security Code) VALUES('$value1', '$value2', '$value3', '$value4','$value5','$value6','$value7','$value8','$value9','$value10','$value11','$value12','$value13','$value14','$value15', ,'$value16',,'$value17',,'$value18',,'$value19',,'$value20')";
if (!mysql_query($sql))
{
die('Error:'.mysql_error());
}
mysql_close();
?>
Column names with space needs to back ticks as
`Last Name`
So in the insert query you need to backtick them.
use back ticks, and overall check at your query :
$sql ="INSERT INTO test(Last Name, Medical Information, First Name, Membership Type, D.O.B, Gender,
Membership Referral, Trainer Required, Membership Number , Contract, House Number/Street, City,
County, Postcode, Tel, E-Mail, Bank Branch, Card Holder Name, Card Number, Security Code)
VALUES('$value1', '$value2', '$value3','$value4','$value5','$value6','$value7','$value8',
'$value9','$value10','$value11',
'$value12','$value13','$value14','$value15', ,'$value16',,'$value17',,'$value18',,'$value19',,'$value20')";
between value15 and value16 you have double , and so on between value 17 and 18.
Clean your query.

Php Post to two tables in Mysql

I'm trying to POST to two tables at the same time. I'm trying to get the DonorID to display in to another table under $description. I'm able to just write any text in the $description, but I need it to be dynamic not static, which is what the text is. I have two tables; the first is accounting and the second is donations. I'm trying to alter the $description='Donation from Donor'; and have the donor that made the transaction be listed where the Donor is. Any suggestions would be greatly appreciated.
Here is my code:
<?php
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support
with the following information: ' . mysql_error());
}
mysql_select_db("$dbname", $con);
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO accounting (date, transactiontype, account,
description, Income, Expense)
VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
mysql_query($sql2);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( 'Location: http://localhost/donations.php' ) ;
?>
As i said i would personaly use mysqli for new project, here a sample of you code with mysqli:
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO `donations` (`date`, `firstname`, `middleinitial`, `lastname`, `organization`, `donorid`, `paymenttype`, `nonmon`, `Income`, `event`) Values ('$date','$firstname','$middleinitial','$lastname','$organization', '$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
$query1 = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$query2 = $mysqli->query($sql2) or die($mysqli->error.__LINE__);
//closing connection
mysqli_close($mysqli);
header( 'Location: http://localhost/donations.php' ) ;
UPDATE
you can add donorid simply placing both vars in the query like:
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('".$date."','".$transactiontype."','".$account."','".$donorid . " " . $description."','".$Income."','".$Expense."')";
this way i just separate donorid and description with a space but you can add anything you want to in plain text:
'".$donorid . " - " . $description."'
After this
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
put
mysql_query($sql);
Please execute the query.
Things I see is ..
First your just executing your $sql2 but not the other $sql statement
Another is while inserting you declared some columns name that is a mysql reserved word (date column)
you should have `` backticks for them..
Refer to this link MYSQL RESEERVED WORDS
additional note: Your query is also vulnerable to sql injection
SQL INJECTION
How to prevent SQL injection in PHP?
Just write after insert on trigger on first table to insert data into another table.
You will have to split $sql2 to 2
1st :-
$sql2 = "INSERT INTO accounting (description) SELECT * FROM donations WHERE donorid='$donorid'"
then another one
"UPDATE accounting SET date='', transactiontype='', account ='', Income='', Expense ='' WHERE description=(SELECT * FROM donations WHERE donorid='$donorid')"
that will take all the information from donoation for the given donorid and list it under description in accounting

How to insert same data into two tables in mysql

Is this possible if I want to insert some data into two tables simultaneously?
But at table2 I'm just insert selected item, not like table1 which insert all data.
This the separate query:
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
Can I insert COUNT(model) at table2?
I have found some script, could I use this?
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
$model = mysql_insert_id($conn);
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
$result = mysql_query($sql,$conn);
}
mysql_free_result($result);
The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.
Generally problems like this are solved by ONE of these methods depending on your exact need:
Creating a view to represent the second table
Creating a trigger to do the insert into table2
Using transactions to ensure that either both inserts are successful or both are rolled back.
Create a stored procedure that does both inserts.
Hope this helps
//if you want to insert the same as first table
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
$result = #mysql_query($qry2);
//or if you want to insert certain parts of table one
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (two) VALUES('$two')";
$result = #mysql_query($qry2);
//i know it looks too good to be right, but it works and you can keep adding query's just change the
"$qry"-number and number in #mysql_query($qry"")
its cant be done in one statment,
if the tables is create by innodb engine , you can use transaction to sure that the data insert to 2 tables
<?php
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$website = $_POST['website'];
if($username == NULL OR $password == NULL OR $email == NULL OR $website == NULL) {
$final_report2.= "ALERT - Please complete all fields!";
} else {
$create_chat_user = mysql_query("INSERT INTO `chat_members` (`id` , `name` , `pass`) VALUES('' , '$username' , '$password')");
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`, `email`, `website`) VALUES ('','$username','$password','$email','$website')");
$final_report2.="<meta http-equiv='Refresh' content='0; URL=login.php'>";
}
}
?>
you can use something like this. it works.
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

Categories