Inserting into two SQL tables using a value from one - php

I am building a simple event registration system using MySQL and PHP. I have four tables:
events: event_id, event_name
instance: instance_id, event_id, date
attendee: attendee_id, attendee_name, attendee_email, attendee_tel
registration: reg_id, attendee_id, instance_id
To clarify, the instance table contains instances of a given event, ie a specific event on a specific date.
When an attendee registers (via a form), I want to write their details to the attendee table, then write the event they have registered for in the registration table, along with the relevant attendee_id, so that when I query the registration table later on, it will show me what event has been registered for and by whom.
However, I'm new to SQL (and databases in general, not to mention PHP as well), so I'm not sure how I can do that given that the attendee_id has only just been generated by adding the attendee to the table. I can easily insert a row into the attendee table with:
$q = "INSERT INTO attendee (attendee_name, attendee_email, attendee_tel)
VALUES ( '$fullname', '$email', '$tel' )";
With the values obviously being grabbed by $_POST from the form. The form also grabs the instance_id, incidentally.
So I just need to know how I can insert the relevant information into the registration table. Any ideas?

After inserting the data to the 1st table (attendee), use the php function mysql_insert_id() to get the last auto increment id.
Then run another query to insert the data to the 2nd table (registration).
In such cases, in order to avoid any data mismatch with the two tables, its better to use BEGIN and COMMIT. So that if any MySQL error occurs in between 2nd query, it will automatically role back.

make these column in tables primary key and auto increment
events: event_id
instance: instance_id
attendee: attendee_id
registration: reg_id
and you can get the last inserted id when you run query to insert in these table by following code immediate after the insert query
$id = mysql_insert_id();
use this appropriately

see mysql_insert_id()
The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the previous INSERT operation.

If you are using mysql_query() for inserting the data into the attendee table, write the mysql_insert_id() in the next line, it will gives you the recently generated attendee_id, store it in a variable and using this variable insert again in the registration table. Something like that:
$q = "INSERT INTO attendee (attendee_name, attendee_email, attendee_tel) VALUES ( '$fullname', '$email', '$tel' )";
$rc=mysql_query($q);
$a_id=mysql_insert_id();
now insert again in 'registration' table with $a_id;

Related

How do I insert a piece of information to an already existing record?

I have an SQL Database setup with rows of data already there. How do I update just one column of one row by grabbing the id (appointmentspage.php?id=1")?
I already have written the code to input the data into the correct position table I want, but I am having trouble selecting the id too
if(isset($_POST["submit"]))
try{
$sql = "INSERT INTO appointments (Notes)
VALUES ('".$_POST["Notes"]."')";
I feel like = $_GET['id']; or WHERE appointments.ApptID = :id should be used, but I can't fathom it.
Currently the 'Notes' column in my SQL table gets an input, but it creates a new empty row with only that data added. I want to select an existing row/entry and add the Notes to that.
On my site I have a set of examples for the basic use cases, you are welcome to check them out.
Your case would be UPDATE query using PDO.
First of all, "insert into an existing record" is called UPDATE. You need to check out your SQL textbook.
And yes, you need something like ApptID = :id in your query. However personally I prefer simple ? marks
So it should be something like
$sql = "UPDATE appointments SET notes=? WHERE ApptID=?";
$stmt= $dpo->prepare($sql);
$stmt->execute([$notes, $id]);
Note three shouldn't be any try or catch stuff around.
You need to define ApptID field as Primary Key with auto-increment field in database define. In MySQL, a primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a NULL value. A table can have only one primary key.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
After that you can use that ApptID for update your existing data using Update query in MySQL

MySQL - make row and update if already exists

I have table with 4 columns: Date, John, Frank, Anthony
I want to make a form which can be filled in by these 3 people everyday and store these values in the database. When John fills in the form today, a new row should be created with the date of today, with his value in the database. When Frank fills in the form 1 hour later (so the same day) his values should also be inserted in the database but in the same row because there's already a row with today's date. But when Anthony fills in the form tomorrow, a new row should me created with the date of tomorrow.
So in short: the program checks if anyone has already filled in the form today. If yes: it just adds the value to the existing row of today in column of the person who filled it in. if not: it makes a new row with the date of today.
I already wrote this code, but the problem is that it makes a new row everytime someone fills in the form, and there should only be a row created if $person is the first one to fill in the form on that day.
$sql = "INSERT INTO table (Date, $name) VALUES (CURDATE(),'$values')";
First make sure that the Date field is a primary or unique key.
Then you can use ON DUPLICATE KEY UPDATE
$sql = "INSERT INTO table (Date, $name) VALUES (CURDATE(),'$values')
ON DUPLICATE KEY UPDATE $name='$values'";
But you really should check for prepared statements in your language (PDO in case of PHP) to prevent SQL injections.
You should change your table.
Instead of a column for each person make a name column so you have:
Date | Name | Values
Make date and person the primary key:
ALTER TABLE 'table' ADD PRIMARY KEY (Date,Name)
Then insert like this:
INSERT INTO table (Date,Name,Values) VALUES (CURDATE(),'$name','$values') ON DUPLICATE KEY UPDATE Values='$values'
Try using REPLACE INTO instead of using INSERT INTO.
EDIT
I just re-read the question - the OP wants to overwrite the data if the user re-submits the form - first time I read it I thought they wanted to keep the original data
An alternative [if you only wanted to keep the original data only], would be using insert ignore : see this answer for a comparison between insert ignore and on duplicate key update: "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
Though you should probably change the table design to be 'date', 'person', 'data' as suggested in another answer

SQL QUERY for inserting a record into PHPMyadmin

What I am trying to achieve is a SQL query which will insert a new product in the product table which has an auto incremented product_id value. However, in the customer table there is also a column for product_id which is a foreign key referencing the product_id value in the product table. Now, I can insert a new product and a new customer, but I would like to know how to write a script that takes a query which I can use in a PHP script which will allow a customer insert a new product so that the keys will relate automatically, so one customer can be related to many products.
I have tried the references in the PHP manual.
$query = mysql_query (" INSERT INTO events
VALUES
( '',
'$event_type',
'$title',
'$description',
'$date',
'$target',
'$add1',
'$add2',
'$ci‌​ty',
'$postcode',
'$country',
'$tick',
NULL
)"
);
For example I have got an events table for the above query and the NULL value at the end of the query is for the foreign key column (user_id) which is from the user table...
If I was a user inserting the event how would I add my id to the event?
First thing is that you should think about your database-model. Is it right, that one customer has got one foreign key to a product? It conflicts that you say that one customer can be related to many products.
Anyway; your problem is, that you insert a product and the ID is automatically generated so you don't know about it, right? You have to write it, read it out right afterwards to make your next insertion. I would recommend a stored procedure to handle this, because your PHP-script should not communicate with your Database as much as this.

Inserting an ID from one table into another when a new record is inserted

I have a form, which contains an employees personal information. I update the form, and it inserts into a table, called employee_info. It updates the table with the details and inserts a NEW ID(employee_id). In my database, I have another table called department_info, and the field which is relevant is department_id. This is the php markup, for inserting data into the database:
$sql_data_array = array('employee_firstname' => $employee_firstname); //other variables go here
if (ACCOUNT_DOB == 'true') $sql_data_array['driver_dob'] = tep_date_raw($driver_dob);
tep_db_perform(TABLE_EMPLOYEES, $sql_data_array);
$employee_id = tep_db_insert_id();
What I need to do is, when the form is updated, and data is inserted into the employee_info table, I need it to insert a new id for employee_id(which is already happening), and also to insert the department_id into the employee_info table.
The department_id is used to login, and I want to show a list of the employees, which belong to the department. Can anyone tell me how I would do this?
When you insert with PHP, most of the implementations return so called last insert id. This is a value of AUTO_INCREMENT column.
Even if your implementation does not support it, there should be a function that returns it.
EDIT:
From your update, this seems to be osCommerce. The problem with your code is that method tep_db_perform is used to insert one or MORE elements. What will happen, if you insert 2 rows? But in simple case, use tep_db_insert_id(), it should return last id.
php function mysqli_insert_id retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). Get this id and use it in other tables.

Inserting into two tables (same DB) how do I get the unique ID from one table?

Firstly please excuse my lack of knowledge for SQL, I have only done basic inserts before.
I am currently improoving a little system that I have, and I want to insert some data that is obtained via _GET (php) into two tables. My problem is as follows.
My first table (table_one) has an auto incrementing value called "id", which I need to obtain, and post over to my second table (table_two).
Because of the way data will be updated at the later date, the ID in table two, is a reference to the ID that is automatically generated upon insert in table one (hence no ID in the code below). (I will be using the ID in table one to do a for loop for each matching ID instance in table_two)
How can I run one query to update one table, then update the 2nd with the unique id obtained from the first table?
My current code is this...
INSERT INTO table_one (valueone,valuetwo,valuethee) VALUES ('$v1','$v2','$v3')
you can use mysql_insert_id() built in command of php this will give you the id of the recently inserted data
mysql_query("insert into.... ");
$a = mysql_insert_id();
mysql_insert_id() after first query will give you id
I want to insert some data that is obtained via _GET
that's wrong. this data should be obtained via POST
Expanding on #Ujjwal's answer, you can do the same just using SQL.
INSERT INTO table1 (x,y) VALUES ('x','y');
INSERT INTO table2 (t1_id, z) VALUES (LAST_INSERT_ID(), 'z');
See: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

Categories