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.
Related
Here is my main PHP code:
<?php
define('dbServer', 'localhost');
$dbUsername = 'root';
$dbPassword = '';
define('dbName', '1');
$dbConnection = mysqli_connect(dbServer, $dbUsername, $dbPassword, dbName);
if(!$dbConnection){
die("Unsuccessful Connection: " . mysqli_connect_error());
}
// All user data will be taken from the form //
$emailAddress = $_POST['emailaddress'];
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$streetAddress = $_POST['streetaddress'];
$phoneNumber = $_POST['phonenumber'];
$comments = $_POST['comments'];
$sql = "INSERT INTO user-submission (email, firstName, lastName, address, phoneNumber, comment) VALUES ('$emailAddress', '$firstName', '$lastName', '$streetAddress', '$phoneNumber', '$comments')";
$result = mysqli_query($dbConnection, $sql);
if (!$result){
die('Error: ' . mysqli_connect_error());
}
?>
My SQL database contains the rows ID, email, firstName, lastName, address, phoneNumber, comment. They are in a database called '1' (for testing purposes) and a table called 'user-submission'.
I have been unable to query this information into my table. I have been successful prior to this on other SQL and PHP pairings. What am I doing wrong this time?
Add this right below the opening php tag at the top then the server will tell you what the error is. Copy the error here if you need help decyfering
error_reporting( E_ALL );
First you need to make changes so hackers don't abuse your code.
Just wait till johnny;drop tables; comes by and wipes out your database.
// All user data will be taken from the form //
$emailAddress = mysqli_real_escape_string($dbConnections,$_POST['emailaddress']);
$firstName = mysqli_real_escape_string($dbConnections,$_POST['firstname']);
$lastName = mysqli_real_escape_string($dbConnections,$_POST['lastname']);
$streetAddress = mysqli_real_escape_string($dbConnections,$_POST['streetaddress']);
$phoneNumber = mysqli_real_escape_string($dbConnections,$_POST['phonenumber']);
$comments = mysqli_real_escape_string($dbConnections,$_POST['comments']);
$sql = "INSERT INTO `user-submission` (email, firstName, lastName, address, phoneNumber, comment) VALUES (?,?,?,?,?,?)";
$prep=$dbConnections->prepare($sql);
$prep->bind_param("ssssss",$emailAddress,$firstName,$lastName,$streetAddress,$phoneNumber,$comments);
#actually puts everything together, and puts it in the database
$prep-execute();
This is my first post on stackoverflow, though I have done extensive research using it along with other sources on a regular basis (including the subject I need help with here.)
To be concise, I am working on a shared session/login/register between a client's site and the EasyAppointments scheduling application. While compiling the config.php for the registration form on my client's site I received this error. I have searched everywhere, please help me understand this:
INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles) VALUES(testing, test, 000000000, 000000000, 123 example street, Birmington, Alabama, 00000, , )INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days) VALUES(TestUser, 0000000000, , , 0, , , , , )
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 ' , 0, , , , , )' at line 2
Here is my config.php code (please excuse my unorthodox variables for sql1/sql2):
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '####');
define('DB_USER','####');
define('DB_PASSWORD','####');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$mobile_number = $_POST['mobile_number'];
$phone_number = $_POST['phone_number'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip_code = $_POST['zip_code'];
$noteboy = $_POST['notes'];
$privs = $_POST['id_roles'];
$email = $_POST['email'];
$nick = $_POST['nick'];
$password = $_POST['password'];
$salt = $_POST['salt'];
$working_plan = $_POST['working_plan'];
$notifications = $_POST['notifications'];
$google_sync = $_POST['google_sync'];
$google_token = $_POST['google_token'];
$google_calendar = $_POST['google_calendar'];
$sync_past_days = $_POST['sync_past_days'];
$sync_future_days = $_POST['sync_future_days'];
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES($first_name, $last_name, $mobile_number, $phone_number, $address, $city, $state, $zip_code, $noteboy, $privs)";
echo $bang;
$banger = "INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days)
VALUES($nick, $password, $salt, $working_plan, $notifications, $google_sync, $google_token, $google_calendar, $sync_past_days, $sync_future_days)";
echo $banger;
$result = mysql_query($bang); mysql_query($banger);
if($result) {
echo "Successfully updated database";
} else {
die('Error: '.mysql_error($con));
}
mysql_close($con);
I doubt you're storing phone numbers as integers, so you should be quoting all those zeroes. SQL doesn't like missing values in the VALUES clause, so you need to fix that to default to a format that's appropriate for your fields, such as empty string, a zero or a NULL. You also need to think about escaping too to avoid errors and SQL injection vulnerabilities - using PDO might be good idea if you're early on in your project, and you should definitely switch to mysqli at the very least.
Your check for query failure only looks at your first query - you should check both.
Anyway, here's how you might apply escaping and quoting to avoid the error you're seeing using your current approach:
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES('".
mysql_real_escape_string($first_name)."','".
mysql_real_escape_string($last_name)."','".
mysql_real_escape_string($mobile_number)."','".
mysql_real_escape_string($phone_number)."','".
mysql_real_escape_string($address)."','".
mysql_real_escape_string($city)."','".
mysql_real_escape_string($state)."','".
mysql_real_escape_string($zip_code)."','".
mysql_real_escape_string($noteboy)."','".
mysql_real_escape_string($privs)."')";
I'm a complete noob to PHP and working with mysql so you know I do however have a great deal of experience with HMTL and CSS. All I need is for a form on my site to upload the information in the form to my database. The problem is that clicking the "submit" button just opens up a blank tab with the address of my .php file in it and displays a blank white screen. The .php is below.
<?php
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
$sql = "INSERT INTO $usertable (firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
$sql="INSERT INTO $usertable (firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('".$_POST[firstName]."', '".$_POST[lastName]."', '".$_POST[streetAddress]."', '".$_POST[city]."', '".$_POST[state]."', '".$_POST[zip]."', '".$_POST[country]."', '".$_POST[email]."', '".$_POST[phone]."', '".$_POST[badgeName]."')";
?>
Now from what I've read this is usually caused by some kind of error in the code. This is difficult for me as I don't know PHP very well and almost everything in the page was taken from other peoples code. Most of it from the code helps from godaddy.com (where the site and database are hosted).
I've tested to make sure that PHP is supported and enabled and it is. I have a form mailer that already functions just fine. I have setup a DNS, I have tried multiple different syntaxes, I have called tech support to see if it is something on their end, I've migrated my sites from windows to linux and every thing I change results in the exact same blank white screen. I have no doubt that after all this it's going to be something that's stupidly easy to fix or blatantly obvious but if anybody could take a look and see what I'm missing I would be very grateful.
My new code after taking in some of the answers posted. I'm still getting a NOTICE and it's still not inserting anything into my database.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
//connect to mysql
$link_id = mysql_connect($hostname, $username, $password);
if (!$link_id) {
die("Unable to connect to database! Please try again later. error:".mysql_errno());
}
//make sure your DB exists
if (!mysql_select_db($dbname)) die ("Connected to mysql but could not connect to the DB. error:".mysql_errno());
//avoid sql_injection
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$streetAddress = mysql_real_escape_string($_POST['streetAddress']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip = mysql_real_escape_string($_POST['zip']);
$country = mysql_real_escape_string($_POST['country']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$badgeName = mysql_real_escape_string($_POST['badgeName']);
//write the query
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
//then you'll need to execute the query :)
mysql_query($sql);
?>
From what I can tell, this code just connects to a database and sets a variable $sql. Are you actually executing the query anywhere? Are you doing anything to print something on the screen?
$_POST[firstName] should be $_POST['firstName'] and so on and
mysql_query($sql) or die('MySQL Error: ', mysql_error());
echo 'Data inserted';
You shouldn't not be using mysql_ now, its deprecated. Do it with PDO
first of all
$_POST[firstname] should be $_POST['firstname']
third
mysql_query($sql,$conn);
second
$conn=mysql_connect(your parameters);
Include this two lines at the very top of your php code:
error_reporting(E_ALL);
ini_set('display_errors', '1');
It is going to enable error reporting and so you will be able to debug your script.
Maybe the problem is that the reading of $_POST variables (and of any array type variable) should be made with 'quotes' when using string index names:
$_POST[firstName] must be written as follows:
$_POST['firstName']
A good way of making this query more secure (against sql injection attacks for example) is to scape the values in POST instead of passing it directly to the query.
$firstName = mysql_real_escape_string($_POST['firstName']);
The value in POST will be scaped so you can pass it to your SQL.
Try to make that will all your variables:
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
Finally you need to actually execute the query:
mysql_query($sql);
If it goes ok you'll see no errors, but be shure to enable error reporting to this script. When everything it's ok remember to remove the error reporting.
Like the other guys said, put the comments in the array reference. That being said you really need to escape the $_POST variables to avoid SQL Injection, its also easier to debug if the code is clearly ordered :)
With ordered code you can type echo "some text"; at any touch point you want to so you can see where the code breaks.
Also switching on error reporting in your php.ini or in code (http://php.net/manual/en/function.error-reporting.php) would be the best bet for watching the errors that you can't predict.
<?php
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
//connect to mysql
$link_id = mysql_connect($hostname, $username, $password);
if (!$link_id) {
die("Unable to connect to database! Please try again later. error:".mysql_errno());
}
echo "connected to mysql";
//make sure your DB exists
if (!mysql_select_db($dbname)) die ("Connected to mysql but could not connect to the DB. error:".mysql_errno());
echo "connected to database";
//avoid sql_injection
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$streetAddress = mysql_real_escape_string($_POST['streetAddress']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip = mysql_real_escape_string($_POST['zip']);
$country = mysql_real_escape_string($_POST['country']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$badgeName = mysql_real_escape_string($_POST['badgeName']);
echo "sanitised input";
//write the query
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
echo "build query: ".$sql;
//then you'll need to execute the query :)
if (mysql_query($sql))
echo "query success";
else
echo "query failed";
//ps you can ignore the last? >
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
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?