Just a heads up, I'm quite new to this but I'd be really thankful if you can drop some knowledge.
I have SQL tables:
Table 'companies' which has the 'company_id' column as primary key.
Table 'users' which has the 'company_id' column as foreign key, referencing the 'companies' table, of course.
Upon signup, two types of users are created.
A manager - who also creates a company
A regular user - who joins the company
I want the regular user to have the company_id of the company he registered to. The user decides to which company he enrolls using a unique company_code.
The code looks like this, so far:
$sql = "SELECT company_id FROM companies WHERE company_code='$company_code';";
$result=mysqli_query($conn, $sql);
$row=mysqli_fetch_assoc($result);
$result=$row["company_id"];
$sql = "INSERT INTO users (firstName, lastName, email, user_uid, user_pwd, role, company_id) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd', '$role', '$result');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?singup=success");
exit();
Everything seems to work just fine, but not the company_id column which is always NULL. Any idea what I'm doing wrong here?
I've already though about assigning the values of the last created user_id and the company_id that matches the company_code to variables and run a query similar to this:
UPDATE `users` SET `company_id` = '$company_id' WHERE `users`.`user_id` = $user_id;
but it really feels like over complicating my existence.
Thanks a lot!
You named your variable $result on line 4.
$result=$row["company_id"];
It should be:
$real_id = $row["company_id"];
Related
hey guys i have this problem..
basicly the first query is jsut for inserting and the 2nd query is for copying data from another table via foreign key. have any idea? im newbie.. :D
else if($payment_description == 'Monthly Subscription'){
$payment_amount = '750';
$sql = "INSERT INTO `paymentlog` ( payment_amount,payment_description,date_payment)
VALUES ( '$payment_amount', '$payment_description','$date_payment')";
$query_run = mysqli_query($conn, $sql);
$sql1 = "INSERT INTO paymentlog (member_id, first_name, last_name)
SELECT member_id, first_name, last_name
FROM member
WHERE member_id = $id";
$query_run1 = mysqli_query($conn, $sql1);
echo ("<script LANGUAGE='JavaScript'>
window.alert('Monthly Payment is been added.');
window.location.href='/PROJECT/MEMBERS/members.php';
</script>");}
I don't think your current code does what you want. You are (attempting to) insert two rows, while, as I understand your question, you want to create a single row in payment_log, with the amount, description and date given as input, and member information that needs to be retrieved from another table using another input paramter.
You can use the insert ... select syntax:
INSERT INTO `paymentlog` (
member_id,
first_name,
last_name,
payment_amount,
payment_description,
date_payment
)
SELECT
member_id,
first_name,
last_name,
:payment_amount,
:payment_description,
:date_payment
FROM member
WHERE member_id = :id
Important notes:
Use prepared statements! Do not concatenate variables in the query string, this is both inefficient and unsafe. Recommended reading: How can I prevent SQL injection in PHP
From a database design standpoint, you should not be duplicating information from table members in table payment_log; storing a reference to the primary key of member is sufficient
hello i tried using mysqli to fetch autoincrement id from the first table to insert it for second table, this is my database design for each table
Table users
id_user PK auto-inc
username
password
nama
role
status
table siswa
id_siswa PK auto-inc
id_tingkatan
nama_siswa
jk_siswa
hp_siswa
nama_ortu
jk_ortu
hp_ortu
id_user
this is what i have tried
$query = "INSERT INTO users
(username, password, nama, role, status)
VALUES ('$name','$password','$nama','$role','$status')";
$koneksi->query($query);
$query = "INSERT INTO siswa
(id_tingkatan, nama_siswa, jk_siswa, hp_siswa,
nama_ortu, jk_ortu, hp_ortu, id_user)
VALUES ('$tingkatan','$nama','$jksiswa','$hpsiswa',
'$namaortu','$hportu', $koneksi->insert_id)";
$koneksi->query($query);
the data is inserted into users table but not to siswa table, any suggestion to fix this?
edit : overlooked variable only ($jkortu) fixed now, thanks
In the latter INSERT, the number of items in the first commalist does not correspond with the number of items in the second commalist. This should throw a syntax error.
You are missing a parameter.
You should always test for mysql errors, otherwise it will fail silently, and you have no idea what is going on:
if (!$server->query($query)) {
throw new Exception($server->error());
}
I have a database of Users and another table for Teachers. Teachers have all the properties as a user but also an e-mail address. When inserting into the DB how can I insert the info, ensuring that the ID is the same for both?
the ID currently is on automatic incrament.
this is what I have at the moment:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$sqlQuery = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result=mysql_query($sqlQuery);
thank you!
use MYSQL function LAST_INSERT_ID()
OR php mysql http://ro1.php.net/manual/en/function.mysql-insert-id.php
why to use separate table for teachers. instead, you can have email field with in user table and additional field with flag (T ( for teacher) and U (for user). Default can be a U. This have following Pros.
Will Not increase table size as email would be varchar
Remove extra overhead of maintaining two tables.
Same Id can be used
If you want to have that as separate table then answer you selected is good one but make sure last insert id is called in same connection call.
After the first insert, fetch the last inserted id:
$last_id = mysqli_insert_id(); // or mysql_insert_id() if you're using old code
Or you could expand your second query and use mysql's integrated LAST_INSERT_ID() function:
$sqlQuery = "INSERT INTO teacher(id, email) VALUES ((SELECT LAST_INSERT_ID()), '$myEmail')";
Try this:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$id = mysql_insert_id();
$sqlQuery = "INSERT INTO teacher(id, email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
Insert data into two tables & using the same ID
First method
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($conn, $sqlQuery1);
$lastID = mysqli_insert_id($conn);
$sqlQuery2 = "INSERT INTO teacher(email, lastID) VALUES ('$myEmail', 'lastID')";
$result2 = mysqli_query($conn, $sqlQuery2);
If the first method not work then this is the second method for you
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($sqlQuery1);
$sqlQuery2 = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result2 = mysqli_query($sqlQuery2);
You can set the Foreign Key in your database table (phpMyAdmin/ MySQL Workbench) to let the Foreign Key follow the Primary Key (ID). Then the data after insert will auto-follow the Primary Key ID.
Example here,
Teachers table set ID - Primary Key
Users table set UserID - Foreign Key (will follow the Teachers table ID)
if you're using MySQL WorkBench, you can refer to this link to set a foreign key.
https://dev.mysql.com/doc/workbench/en/wb-table-editor-foreign-keys-tab.html
Hope I can help any of you.
Though you can use the LAST_INSERT_ID() function in order to get the last insert id, the best approach in this case is to create a column reference to user id table.
teacher
id | user_id | email
So the teacher.id could be anyting, but the user_id column is the real reference to user table.
If you use InnoDB table, you can make the database consistent using Foreign keys
You Should Use A Transaction In MySQL. First insert In One Table And GET LAST_INSERT_ID().
Insert LAST_INSERT_ID() In Second Table.
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$sqlQuery = "INSERT INTO teacher(LAST_INSERT_ID(), email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
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 recently asked a question about writing to multiple tables: PHP/MySQL insert into multiple data tables on submit
I have now tried out this code and there are no errors produced in the actual code but the results I am getting are strange. When a user clicks register this 'insert.php' page is called and the code can be found below.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$institution = $_POST["institution"];
$conn = pg_connect("database connection information"); //in reality this has been filled
$result = pg_query($conn, "INSERT INTO institutions (i_id, name) VALUES (null, '$institution') RETURNING i_id");
$insert_row = pg_fetch_row($result);
$insti_id = $insert_row[0];
// INSTITUTION SAVED AND HAS ITS OWN ID BUT NO MEMBER OF STAFF ID
$resultTwo = pg_query($conn, "INSERT INTO staff VALUES (NULL, '$username', '$password', '$insti_id'");
$insert_rowTwo = pg_fetch_row($resultTwo);
$user_id = $insert_rowTwo[0];
// USER SAVED WITH OWN ID AND COMPANY ID
// ASSIGN AN INSTITUTION TO A STAFF MEMBER IF THE STAFF'S $company_id MATCHES THAT OF THE
// INSTITUION IN QUESTION
$update = pg_query($conn, "UPDATE institutions SET u_id = '$user_id' WHERE i_id = '$insti_id'");
pg_close($conn);
?>
What the result of this is just the browser waiting for a server response but there it just constantly waits. Almost like an infinite loop I'm assuming. There are no current errors produced so I think it may be down to a logic error. Any ideas?
The errors:
RETURNING clause is missing in the second INSERT statement.
Provide an explicit list of columns for your second INSERT statement, too.
Don't supply NULL in the INSERT statements if you want the column default (serial columns?) to kick in. Use the keyword DEFAULT or just don't mention the column at all.
The better solution:
Use data-moidifying CTE, available since PostgreSQL 9.1 to do it all in one statement and save a overhead and round trips to the server. (MySQL knows nothing of the sort, not even plain CTEs).
Also, skip the UPDATE by re-modelling the logic. Retrieve one id with nextval(), and make do with just two INSERT statements.
Assuming this data model (you should have supplied that in your question):
CREATE TABLE institutions(i_id serial, name text, u_id int);
CREATE TABLE staff(user_id serial, username text, password text, i_id int);
This one query does it all:
WITH x AS (
INSERT INTO staff(username, password, i_id) -- provide column list
VALUES ('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING user_id, i_id
)
INSERT INTO institutions (i_id, u_id, name)
SELECT x.i_id, x.user_id, '$institution'
FROM x
RETURNING u_id, i_id; -- if you need the values back, else you are done
Data model
You might think about changing your data model to a classical n:m relationship.
Would include these tables and primary keys:
staff (u_id serial PRIMARY KEY, ...)
institution (i_id serial PRIMARY KEY, ...)
institution_staff (i_id, u_id, ..., PRIMARY KEY(i_id, u_id)) -- implements n:m
You can always define institution_staff.i_id UNIQUE, if a user can only belong to one institution.