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
Related
<?php
$fname= $_REQUEST['firstname'];
$lname= $_REQUEST['lastname'];
$email= $_REQUEST['email'];
$pass = $_REQUEST['password'];
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect ');
}
$ins1 = "INSERT into signup values( '$fname' , '$lname', '$email','$pass')";
$select = mysql_select_db('ait', $conn);
if(! $select)
{
die("<h2> incorrect input <h2>".mysql_error());
header('location:index.php');
}
$in1 = mysql_query($ins1);
if (!$in1)
{
die("<h2> incorrect input <h2>".mysql_error());
header('location:signed.php');
}
mysql_close($conn);
header('location:signed.php');
exit;
?>
I am making a sign up form and adding this in the database but I am getting this error "incorrect input Column count doesn't match value count at row 1". I am not inserting id from this code as it is auto increment.
Write down the names of columns explicitly in the query.
INSERT into signup(first_name,last_name,email,password)
values( '$fname' , '$lname', '$email','$pass')
Took at look at SQL injection. Passing parameters like this is not a safe approach.
If id is autoincrement (and it is the only column you skip and the first one in the table), use:
$sql = "INSERT into signup values (null, '$fname' , '$lname', '$email','$pass')";
This way, you let mysql fill in the id value, but you still need to specify it.
An alternative is to use:
$sql = "INSERT into signup (col1, col2, col3, col4) values ('$fname' , '$lname', '$email','$pass')";
Where you replace col* with the actual column names.
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
I'm on ubuntu running on apache2.
<?php
$con = mysqli_connect("localhost", "root", "password", "loops");
if (!mysqli_connect_errno()) {
echo "Error to connect: ".mysqli_connect_error();
}
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
echo "First: ".$firstName."<br />Age: ".$age;
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values (".$firstName.",".$lastName.",".$age.")";
if (!mysqli_query($con)) {
die("Error :".mysqli_error($con);
}
echo "1 added";
mysqli_close($con);
?>
I don't know what to do now, but the error seems to be on the '$sql', 'cause when I put that
under a comment, the rest works...
You forgot the infamous mistake of wrapping the varchar variables with single quote '
"INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
Additionally, It's highly risky for you, not be using protections against SQL Injections
Try this, mysqli_query($con, $sql) You need to execute the query so that it will store into the database
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
if (!mysqli_query($con, $sql)) {
...................^
die("Error :".mysqli_error($con);
}
Try this:
$sql = "INSERT INTO persons (`FirstName`, `LastName`, `Age`) values (".$firstName.",".$lastName.",".$age.")";
If this doesn't work, what error do you get.
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?
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