I have two tables the first one is "student":
id (PK) "auto_inc"
student_name
email
The second one is "bill":
id (PK) "auto_inc"
student_id (FK -> id)
total_balance
I am trying to auto-insert the last 'id' into 'student_id' when I add a new student in the same query.
This is my query to add a new student to the table
insert into student (name, major, emailAddress)
values ( :name, :major, :emailAddress )
For example:
id= 1
student_name= "Mike"
email= "mike#mail.com"
bill table:
id= 1
student_id= 1 "from 'student' table"
total_balance= 100
I do not have much experience with SQL DB, I am recently using it.
I can advice next approach:
create table student with unique key email
create table student (
id int primary key auto_increment,
student_name varchar(255),
email varchar(255) unique key
);
use next PHP code:
<?php
$name = "Barry Block";
$email = "barry.b#gmail.com";
$balance = 500;
$student_sql = "
insert into student (student_name, email)
values ( :name, :emailAddress )";
$stmt = $pdo->prepare($student_sql);
$stmt->execute([':name'=>$name, ':emailAddress'=>$email]);
$bill_sql = "
insert into bill (student_id, total_balance)
select id, :balance from student where email = :emailAddress";
$stmt = $pdo->prepare($bill_sql);
$stmt->execute([':balance'=>$balance, ':emailAddress'=>$email]);
Test MySQL & PHP code online
Related
I want to use one form to insert into two different Microsoft sql tables. I tryed to use 2 inserts, but didnt work.
if (isset($_GET['submit'])) {
$sth = $connection->prepare("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
echo "INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter',$Datum,'$Verbleib','$DUTNr')";
$sth->execute();
if($sth)
{
echo "";
}
else
{
echo sqlsrv_errors();
}
$MID = $connection->prepare("MAX(MID) as MID FROM DB.dbo.Fehler WHERE DB.dbo.Fehler.TestaufstellungID = '". $TestaufstellungID . "'");
$MID->execute();
$sth2 = $connection->prepare("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES ($MID, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$sth2->execute();
To understand MID is the Primary key of table Fehler and ist the foreign key in the second table Fehlerinfo
Thats why i have the select work around to get the last MID and want to save it in a variable $MID to insert it into the second table.
Is there a smarter solution possible?
As I mentioned in the comments, generally the better way is to do the insert in one batch. This is very over simplified, however, should put you in the right direction. Normally you would likely be passing the values for the Foreign Table in a Table Value Parameter (due to the Many to One relationship) and would encapsulate the entire thing in a TRY...CATCH and possibly a stored procedure.
I can't write this in PHP, as my knowledge of it is rudimentary, but this should get you on the right path to understanding:
USE Sandbox;
--Couple of sample tables
CREATE TABLE dbo.PrimaryTable (SomeID int IDENTITY(1,1),
SomeString varchar(10),
CONSTRAINT PK_PTID PRIMARY KEY NONCLUSTERED (SomeID));
CREATE TABLE dbo.ForeignTable (AnotherID int IDENTITY(1,1),
ForeignID int,
AnotherString varchar(10),
CONSTRAINT PK_FTID PRIMARY KEY NONCLUSTERED(AnotherID),
CONSTRAINT FK_FTPT FOREIGN KEY (ForeignID)
REFERENCES dbo.PrimaryTable(SomeID));
GO
--single batch example
--Declare input parameters and give some values
--These would be the values coming from your application
DECLARE #SomeString varchar(10) = 'abc',
#AnotherString varchar(10) = 'def';
--Create a temp table or variable for the output of the ID
DECLARE #ID table (ID int);
--Insert the data and get the ID at the same time:
INSERT INTO dbo.PrimaryTable (SomeString)
OUTPUT inserted.SomeID
INTO #ID
SELECT #SomeString;
--#ID now has the inserted ID(s)
--Use it to insert into the other table
INSERT INTO dbo.ForeignTable (ForeignID,AnotherString)
SELECT ID,
#AnotherString
FROM #ID;
GO
--Check the data:
SELECT *
FROM dbo.PrimaryTable PT
JOIN dbo.ForeignTable FT ON PT.SomeID = FT.ForeignID;
GO
--Clean up
DROP TABLE dbo.ForeignTable;
DROP TABLE dbo.PrimaryTable;
As i mentioned the answer how it works for me fine atm.
if (isset($_GET['submit'])) {
$failInsert = ("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
$failInsert .= ("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES (NULL, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$failInsert .= ("UPDATE DB.dbo.Fehlerinfo SET DB.dbo.Fehlerinfo.MID = i.MID FROM (SELECT MAX(MID)as MID FROM DB.dbo.Fehler) i WHERE DB.dbo.Fehlerinfo.TestID = ( SELECT MAX(TestID) as TestID FROM DB.dbo.Fehlerinfo)");
$sth = $connection->prepare($failInsert);
$sth->execute();
}
Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.
I am working on an events calendar using PHP and MySQL (V5.1) where the admin would add an event, and then an attendance list for that event would be created as well. I have three tables: events, attendance and members. So far I can create the event using information that is entered thorugh a PHP form. I'm trying to update the attendance table by inserting the event id from the event that has just been created, as well as pulling in the list of members (using their member ID) from the members table. Nothing is being added to attendance the table though. Can someone let me know what I should I be doing differently?
Some of the fields I am using in the tables:
Events: event_ID (Primary key, auto-increment), name, location, date
Attendance: attendance_ID (Primary key, auto-increment), event_ID, member_ID, attending
Members: member_ID (Primary key, auto-increment), name, email
enter code here
Here is the code:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT LAST_INSERT_ID(), members.member_ID FROM members");
if ($query1 and $query2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
You could use mysql_insert_id()
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$insert_id = mysql_insert_id() ;
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT {$insert_id}, members.member_ID FROM members") ;
A couple of important points. First, if you getting your last insert ID you should execute LOCK and UNLOCK queries first:
LOCK TABLES events WRITE;
UNLOCK TABLES
Second, you can use the mysqli_insert_id() method to get the ID of the last insert. This means that you must have an AUTO_INCREMENT field in the table you are inserting.
Put VALUES into $query2 to form a correct SQL-statement:
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) **VALUES (**SELECT LAST_INSERT_ID(), members.member_ID FROM members");
I have a PostGreSQL database with the following data model:
CREATE TABLE staff (s_id serial UNIQUE, name, username, password, email)
CREATE TABLE institution (i_id serial UNIQUE, name);
CREATE TABLE isStaffOf (i_id, s_id); //foreign key references
When a user submits the form I have a PHP script which writes the information to first two data tables and that automatically generates the s_id and i_id values. Great!
I've tried out a few PHP modifications to get the system writing both the s_id and i_id into the isStaffOf relation so it can enforce the explicit 1..1 relationship required for my project but on submit it says I have an insufficient data type. See below for the PHP code.
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$institution = $_POST["institution"];
$conn = pg_connect("host=***** port=**** dbname=****** user=**** password=******");
$staffWrite = pg_query("INSERT INTO staff(name, username, password, email) VALUES ('$name', '$username', '$password', '$email')");
$instiWrite = pg_query("INSERT INTO institution(name) VALUES ('$institution')");
$instiFK=pg_query("SELECT i_id FROM institution WHERE name='$institution'");
$staffFK=pg_query("SELECT s_id FROM staff WHERE name='$username'");
$sql=("INSERT INTO isstaffof(i_id, s_id) VALUES ('$instiFK', '$staffFK')");
$result = pg_query($sql);
That is the script I have at the moment but its not working. Any ideas on how to fix this so that when a user submits all the data tables will be filled and the referential integrity enforced? I'm almost there and still trying things out but to no avail.
The error message:
ERROR: invalid input syntax for integer: "Resource id #4" LINE 1: INSERT INTO isstaffof(i_id, s_id) VALUES ('Resource id #4', ...
Please let me know if you need more explanation but I'm sure its clear what I want to achieve and I'm convinced I can do it without so many pg_query calls.
As of PostgreSQL version 9.1, you can use a single query to INSERT in all 3 tables, a writable common table expression:
WITH
step_1 AS(
INSERT INTO staff (name) VALUES('Frank') RETURNING s_id
),
step_2 AS (
INSERT INTO institution (name) VALUES('PostgreSQL') RETURNING i_id
)
INSERT INTO isStaffOf (i_id, s_id) SELECT i_id,s_id FROM step_1, step_2;
Simple, fast and reliable.
You could do some other tricks as well, when some records already exists and just want to select the primary key value.
WHEN creating the isstaffof table, you at least have to specify the datatypes, and you can specify they are foreign keys.
CREATE TABLE isstaffof
(i_id BIGINT REFERENCES institution(i_id)
, s_id BIGINT REFERENCES staff(s_id)
);
NOTE: avoid using MixedCase for identifiers. It might cause terrible problems, if you ever have to port to a different DBMS platform.
UPDATE: Just put it in a plain INSERT INTO ... SELECT ... FROM ... statement.
CREATE TABLE staff (s_id serial UNIQUE, sname varchar);
CREATE TABLE institution (i_id serial UNIQUE, iname varchar);
CREATE TABLE isstaffof
(i_id BIGINT REFERENCES institution(i_id)
, s_id BIGINT REFERENCES staff(s_id)
);
INSERT INTO isstaffof(i_id,s_id)
SELECT i.i_id,s.s_id
FROM staff s, institution i
WHERE i.iname='$institution'
AND s.sname = '$staff'
;
Now, you can wrap that into your front-end code.
You'll have to fetch the result with pg_fetch_assoc or something similar. The way you're using it now you're passing the whole pg_query resource as an integer - obviously php can't convert that to a valid integer.
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$institution = $_POST["institution"];
$conn = pg_connect("host=***** port=**** dbname=****** user=**** password=******");
$staffWrite = pg_query("INSERT INTO staff(name, username, password, email) VALUES ('$name', '$username', '$password', '$email')");
$instiWrite = pg_query("INSERT INTO institution(name) VALUES ('$institution')");
$instiFK=pg_query("SELECT i_id FROM institution WHERE name='$institution'");
$rowInsti = pg_fetch_assoc($instiFK);
$staffFK = pg_query("SELECT s_id FROM staff WHERE name='$username'");
$rowStaff = pg_fetch_assoc($staffFK);
$result = pg_query("INSERT INTO isstaffof(i_id, s_id) VALUES (".$rowInsti['i_id'].", ".$rowStaff['s_id'].")");
As an alternative you could probably use pg_last_oid directly after every insert to get the id. (Even more beautiful would the RETURNING-solution be. Just read the comments on the php.net page)
I have a mysql table called
jos_users_quizzes with the following columns:
id
quiz_i
duser_id
I have a second table called jos_users with this columns
id
name
username
department
the user_id on first table is linked with the id of second table so quiz_id = id (jos_users)
How can build a query to multiple insert the ids of a selected department into the jos_users_quizzes table... IN ONE CLICK
I am thinking a sub query or a loop will do , but no sure how to contruct the query.
I need to select all user ids from selected department. For example have a list of departments, and once the department is selected , select all ids pertaining that department and insert all the Ids into the other table (quizid , (alldepartment ids)
Thanks in advance!
Code from and ASP.NET form to insert ....
string quizidselected = DropDownList1.SelectedValue;
string deptselected = ListBox2.SelectedValue;
//OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (quiz_id,user_id) VALUES (' " + quizidselected + " ',677)");
OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT id, ' " + quizidselected + " ' FROM jos_users WHERE department = ' " + deptselected + " '");
Based on my interpretation of what you want...
INSERT INTO jos_users_quizzes (user_id, quiz_id)
SELECT id, :new_quiz_id
FROM jos_users
WHERE department = :department
If you set the id using auto increment, then you can do something like this
insert into jos_users_quizzes (quiz_i) select id from jos_users;
It is easy if you know keyword like email address, department id or department name.
For example:
$depname = "Logistics"; // PHP // department name
$quizid = "Quiz-12"; // PHP // quiz name
Then make insert query:
<?php
$query = "INSERT INTO `to_table` (user_id, quiz_id)
SELECT id, '$quizid' FROM `from_table`
WHERE department = '$depname'";
?>
For more compatibility you can use Lower case if you obtained values from web page, like:
<?php
$query = "INSERT INTO `to_table` (user_id, quiz_id)
SELECT id, LOWER('%$quizid%')
FROM `from_table`
WHERE department like LOWER('%$depname%')";
?>
Use addslashes command for protecting database when you insert data from web page:
<?php
$query = "INSERT INTO `to_table` (user_id, quiz_id)
SELECT id, LOWER('%".addslashes($quizid)."%')
FROM `from_table`
WHERE department like LOWER('%".addslashes($depname)."%')";
?>