PHP Creating entries in different tables - php

I'm currently working on a project and stuck with something.
I am looking for a way to join two different tables. When you create an entry in one table, it will automatically create an entry in another table.
For example lets say I am creating new patients for a system. When I input all data in to the form and click submit, all of the data is then stored in the patients table under the unique patient id.
Now where I have created a row for Bob in the patients table, I would like for it to also create a row for Bob in the accounting table. So that the accounting data would be tied with the patient data.
So when I submit for a new patient, I would it to also create a new row in the accounting table that can refer to the patient it's created for.
I am not sure if I made my question clear..
EDIT:
Thanks for all the help! I managed to get it up and working with the following..
<?
session_start();
include "database_connect.inc";
$sql="INSERT into patients SET patient_fname='".addslashes($_POST['fname'])."',
patient_initial='".$_POST['initial']."',
patient_lname='".addslashes($_POST['lname'])."',
address='".addslashes($_POST['address'])."',
city='".addslashes($_POST['city'])."',
state='".$_POST['state']."',
zipcode='".$_POST['zip']."',
phone1label='".$_POST['phone1label']."',
phone1='".$_POST['phone1']."',
phone2label='".$_POST['phone2label']."',
phone2='".$_POST['phone2']."',
phone3label='".$_POST['phone3label']."',
phone3='".$_POST['phone3']."',
phone4label='".$_POST['phone4label']."',
phone4='".$_POST['phone4']."',
dateofinjury='".$_POST['dateofinjury']."',
office_location='".$_POST['officelocation']."',
law_office1='".$_POST['lawoffice1']."',
law_office2='".$_POST['lawoffice2']."',
insurance1='".$_POST['insurance1']."',
pip='".$_POST['pip']."',
claim1='".$_POST['claim1']."',
insurance3='".$_POST['insurance3']."',
claim3='".$_POST['claim3']."'";
$result = mysql_query($sql,$cn);
if (!$result) die("ERROR - Query failed while trying to add a new patient record!<br>".$sql);
$sql="INSERT INTO accounts (patient_id,patient_name,patient_lname) VALUES(LAST_INSERT_ID(),'".$_POST['fname']."','".$_POST['lname']."')";
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
header("location:createpatient.php");
?>

Based on your question, I prefer suggest you this concept:
example:
table1 name: patients
table2 name: accounting
indicator:
patient_id in patients table1
accounting_id in accounting table2
then, let's do it!:
<?php
$sql="INSERT INTO patients (patient_fname, ...)
VALUES ('$_POST[patient_fname]','....')";
mysql_query($sql);
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
$getIdInTable1 = mysql_query("SELECT LAST_INSERT_ID() AS patient_id
FROM patients");
$setID = mysql_fetch_assoc($getIdInTable1);
$sql="INSERT INTO accounting (patient_id, ....)
VALUES ({$setID['accounting_id']}, '$_POST['patient_id']','....')";
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
mysql_close($db_server);
header("location:createpatient.php");
exit();
?>
'Hope this really help you.

At first give it a try, then ask where you get actually stuck.
If i were you, i would try something like this.
BEGIN;
INSERT INTO patients(name,details)
VALUES('test', 'test');
INSERT INTO patient_profiles (patient_id, information)
VALUES(LAST_INSERT_ID(),'something useful');
COMMIT;
Please refer some manual.

it s better than You use a manual progressive max code to join tables instead of id

Related

Insert id from from one table and insert it into another one. Mysql + PHP [duplicate]

This question already has answers here:
How to get the last field in a Mysql database with PHP?
(5 answers)
Closed 9 years ago.
I am working on a register user form and I have two tables in mysql. What I want to do is when a new user has registered, take the id (which primary key) of that user and insert it into another table. What is the best way to do that?
Thanks in advance.
You need to use mysql_insert_id for this purpose. Here is an example:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
First insert the user details into users table and get inserted user id using mysql_insert_id. and use that user id to insert into another table.
AS ON GETTING IT ON PHP
GET LAST INSERT ID HERE
BUT IF YOU INTEND TO GET IT USING MYSQL QUERY
use stored procedure to store last insert id to a variable then generete your second query
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
SET #last_id_in_T1 = LAST_INSERT_ID();
INSERT INTO T2 (col1,col2) VALUES (#last_id_in_T1,val2);
or direct insert after your first insert
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
INSERT INTO T2 (col1,col2) VALUES (LAST_INSERT_ID(),val2);
Use any of transaction query for writing:
Following is in CI pattern:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('AN SQL QUERY...');
if(!$this->db->trans_complete()){
$this->db->trans_rollback();
}
$query1= "INSERT INTO employee ( username, email,...)
VALUES ('".$_POST["username"]."', ...)";
if($result1 = mysql_query($query1))
{
$emp_id = mysql_insert_id(); // last created id by above query
$query2= "INSERT INTO dept ( emp_id, dept_name, ...)
VALUES ('".$emp_id."', '".$_POST["dept_name"]."',...)";
if($result2 = mysql_query($query2))
{
//success msg
}
}
Another neat way to do it at do it at Database level itself is to used Stored Procedure
Look at this solution to see an example of how to do it. You will have to check how Stored procedures work in your specific database to get the specific syntax. This makes it error free even if someone refactors or moves around the code and more efficient.
Using trigger the Mysql on database-level. For example, I have two tables:
user(id int primary key, nombre varchar(50));
replication(id_r int primary key, nombre_r varchar(50));
Using the trigger:
create trigger user_r after insert on user
for each row
insert into replication(id_r, nombre_r)
select u.id, u.nombre
from user u
where u.id=NEW.id and u.nombre=NEW.nombre;

modifying tables in my database

I have database with a table called members, which stores data for my admin,client,technicians all in one.But now I want to break this table into three separate tables as admin table,client table and techs table.As I have now written queries based on the members table I want to keep the common fields which were used in queries in the members table as they are now.Therefore I reduced the members table only to have fields ID,Name,UserName,Password,Level,Category.Throughout the site it is recognized if the user is a admin,client,or technician by setting levels(which corresponds to Level field).
When inserting data I tried using this code.First insert the common fields to members and then depending on the level write separate queries specifying to which table should data be inserted.
if($_POST['Submit']){
if(mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE UN='$r[UN]' AND ID!='$r[ID]' "))) {
?><script language="javascript" type="text/javascript">alert('Username already exsits.Please enter another.');
</script>
<?php
}
else {
mysql_query("INSERT INTO members (Name,UN,Password,Level,Category) VALUES ('$r[Name]','$r[UN]','$r[PW]','$r[Level]','$r[Category]')");
$row=mysql_query("SELECT * FROM members WHERE Name='$r[Name]'") or die('query unsuccesful');
if ($row['Level']==1){
mysql_query("INSERT INTO client(Name,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
}
elseif($row['Level']==2){
mysql_query("INSERT INTO techs (Name,,Category,Company,Price,Comments,Rate,Qualifications,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Category]','$r[Company]','$r[Price]','$r[Comments]','$r[Rate]','$r[Qualifications]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
}
else{
mysql_query("INSERT INTO admin (Name,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
}
if(!$user){
$user=$r;
$_SESSION['user']=$r;
}
But data gets inserted only to members table and nothing goes for client,techs or admin.Any idea how I can mend this please
You are not fetching data on the 2nd select.
$row=mysql_query("SELECT * FROM members WHERE Name='$r[Name]'") or die('query unsuccesful');
if(mysql_fetch_array($row)) {... }

Multiple queries MySQL PHP

Is there is proper way to do this. I want to calculate the average rating for a table and update the result in another table simultaneously. Im new to PHP and MYSQL and I would appreciate any help
$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
$avg_query="SELECT ROUND(AVG(rating),0) FROM review WHERE name =\"$restaurant\"";
$avg_result=mysql_query($avg_query);
$avg_row=mysql_fetch_array($avg_result);
$rating=$row['ROUND(AVG(rating),0)'];
if($avg_result)
{
$update_query= "UPDATE restaurant SET rating=\"$rating\" WHERE name =\"$restaurant\"";
$update_result=mysql_query($update_query);
}
}
else
{
}
Thanks!
UPDATE restaurant
SET rating= (SELECT ROUND(AVG(rating),0) FROM review WHERE name ='$restaurant')
WHERE name ='$restaurant'
I would combine the two into one like this:
$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
$avg_query="UPDATE restaurant a SET rating=(SELECT ROUND(AVG(rating),0) FROM review WHERE name =a.name) WHERE name ='".$restaurant."'";
$avg_result=mysql_query($avg_query);
}
else
{
}
Having said that, you should move over to either PDO or mysqli as the mysql_* functions are depreciated.
Another option is to use a mysql trigger. For example (don't hold me to the syntax):
CREATE TRIGGER after_insert_review
AFTER INSERT ON review
FOR EACH ROW
BEGIN
UPDATE restaurant
SET rating = (SELECT ROUND(AVG(rating),0) FROM review WHERE name = NEW.restaurant)
WHERE name = NEW.restaurant;
END
Again as mentioned by others use PDO or MySQLi.

Auto-creating a "link" table between 2 main tables (ex table EmployeeProject from Employee and Project tables)

I have these 2 tables, Medication containing: IDMedication, IDCategory, Name, and Supplier, containing: IDSupplier, Name. I want to automatically create a relationship table, MedicationSupplier, containing: IDMedication and IDSupplier as keys, Price, and Quantity.
My idea was to have a main page where i request the following data: (Medication)Name, IDCAtegory, (Supplier)Name, Price, Quantity.
I'm not sure if i'm doing the right thing here.
So this is what i'm receiveing in the .php where i do the insert:
$Denumire=$_POST['Denumire']; //Medication Name
$IDCategorie=$_POST['IDCategorie']; //IDCategory
$Nume=$_POST['Nume']; //Supplier Name
$Pret=$_POST['Pret']; //Price
$Stoc=$_POST['Stoc']; //Quantity
And this is my insert:
$q_produse = "INSERT INTO produse VALUES ('','$IDCategorie','$Denumire')";
$q_prodfurniz = "INSERT INTO produsfurnizor VALUES ('','$IDFurnizor','$Pret','$Stoc')";
mysql_query($q_produse) or die($error);
mysql_query($q_prodfurniz) or die($error);
mysql_close();
My main problem at the moment is that i don't know how to insert IDMedication in the relationship table. Any help / suggestions of improving my code would be greatly appreciated. Thanks!
It sounds like you're needing to get the auto id created for the rows in your Medication and Supplier tables. You can use mysql_insert_id()
$q_produse = "INSERT INTO produse VALUES ('','$IDCategorie','$Denumire')";
$q_prodfurniz = "INSERT INTO produsfurnizor VALUES ('','$IDFurnizor','$Pret','$Stoc')";
mysql_query($q_produse) or die($error);
$produse_id = mysql_insert_id();
mysql_query($q_prodfurniz) or die($error);
$prodfurniz_id = mysql_insert_id();
$q_relationTable = "INSERT INTO MedicationSupplier VALUES ('$produse_id','$prodfurniz_id')";
mysql_query($q_relationTable) or die($error);
mysql_close();
Documentation on mysql_insert_id() is available at http://php.net/manual/en/function.mysql-insert-id.php
http://us2.php.net/mysql_insert_id
retrieves the last autoincremented value, in this case, IDMedication.

php/mysql creating duplicate records with multiple tables

I'm building a database for making hotel reservations. One table called "reservations" holds the general details of the reservation, while another called "rooms" holds details about specific rooms (each reservation has many rooms, each room belongs to only one reservation).
I would like to be able to easily generate duplicate reservations records (except for the primary key, of course). My problem is in generating the rooms data as an array which is then inserted into the rooms table while being associated to its reservation.
I've come as far as the following trivial code (stripped down to the bare essentials for discussion purposes).
if (isset($_POST['action']) and $_POST['action'] == 'Duplicate')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
// retrieve reservation
$sql = "SELECT type_of_reservation FROM reservations WHERE id='$id'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$type_of_reservation = $row['type_of_reservation'];
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
$id = mysqli_insert_id($link);
// retrieve rooms
$sql = "SELECT reservation_id, in_date FROM rooms WHERE reservation_id='$id'";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($result))
{
$rooms[] = array('reservation_id' => $row['reservation_id'], 'in_date' => $row['in_date']);
}
The big question is, now what? Everything I've tried either generates an error or no new entries, and I can't seem to find any discussion that addresses this specific need. Thanks for your help.
PeterC, there is no code listed that shows you inserting the ROOM record information. In the //retrieve room section of your code, you are pulling the data and putting it into an array. If you really want to create a duplicate records, I would use in insert inside the database, then you don't have to pull the records out just to put them back in.
The bit of code you want will be something like this. It will be in place of the //retrieve rooms code you have listed: (psuedo code) [note: $id represents the newly selected id from your sql insert for the duplicated reservation]
INSERT INTO rooms(res_id, other, data)
SELECT $id, other, data FROM rooms WHERE id = $_POST['id'];
This will allow you to duplicate the room data, adding the new reservation_id right inside the database. No need to pull out the records, create inserts, and then put them back in. You can read more about INSERT INTO ... SELECT statements here: http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
//ADD HERE CODE BELOW
$id = mysqli_insert_id($link);
with mysql_insert_id you get the inseted id, but you should insert it into db.. so add
mysqli_query($link, $sql);
before retrieving data
If you simply need to duplicate records, you can do it this way:
INSERT INTO
reservations
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
`all`,
`other`,
`column`,
`names`
FROM
reservations
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)
Then for the rooms use the last inserted id (for instance retrieved with mysql_insert_id), like this:
INSERT INTO
rooms
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
$newReservationId, # this is the new reservation id
`all`,
`other`,
`column`,
`names`
FROM
rooms
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)

Categories