Mysqli insert into multiple table with auto increment - php

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());
}

Related

get values from database and work on them

<?php
include('connection.php');
/* code for id goes here */
$q2= "select MAX(id) from usertable";
echo mysqli_query($sql,$q2);
$name=$_POST['name'];
$username=$_POST['usrname'];
$password=$_POST['psw'];
$dob=$_POST['date'];
$query="insert into usertable(name, username, password, dateofbirth) values('$name', '$username','$password','$dob')";
if(mysqli_query($sql,$query))
{
echo "Registered successfully";
}
?>
This is my insert command to register a user in my database. However the database contains a column named id which is the primary key. How do I fetch the id before executing the insert query so that it fetches the last id and increments it by 1 and inserts it in the db along with the other data. The id is numeric and I want the program to perform the operation itself rather than the user entering the data of the id. Please help.
You need to set your id field to auto incement and your database will do it automatically:
ALTER TABLE usertable MODIFY COLUMN id INT auto_increment;
You need to write a query
SELECT MAX(id) FROM usertable
and get the result from that and then increment that value by 1 and then set that value in id field.

update on multitable relation

I have three tables users_tbl, skill_tbl, user_skill_tbl where
users_tbl have 1 to many relations with user_skill_tbl(auto increment)
and skill_tbl have 1 to many relations with the user_skill_tbl.
user_skill_tbl have user_skill_id, skill_id and user_id.
I don't have a problem in inserting the data in the tables.
I have a form where users detail and multiple check option of skill(i get the skill_id only) is there.
when the from is filled, first the user's table is inserted then the last inserted id is taken and the user_skill_tbl is inserted.
But My problem is when I have to update the user_skill_tbl I have used
$skill = $_POST['skill_id'];
for($i=0;$i < count($skill); i++){
$name[$i]= mysqli_escpae_string($con,$skill[$i]);
$query = "update into user_skill_tbl (skill_id)
values ('$skill_id') where user_id = '$user_id'"
after the query is executed the last id of the skill_id is updated on all the skill_id in the user_skill_tbl. I know that I should manipulate along with the user_skill_id but I am not being able to figure it out
I guess you are mixing up the update and insert syntax with "update into". It's "update tablename" or "insert into tablename".
I am not sure how you store your data in user_skill_tbl but if, as I guess, for each user you only store the records related to his/her skills, you need to first delete all the skills for the current user, something like:
$query = "delete from user_skill_tbl where user_id = '$user_id'"
and then add each skill in your for loop:
$query = "insert into user_skill_tbl (skill_id, user_id) values
('$skill_id', '$user_id')
Put everything in a transaction to avoid inconsistencies if something goes wrong during the execution.

Get sql Id and insert it into another query instantly

I have two tables first called messages and the other called messages_reply.
I used this code to insert into messages table:
$query = "INSERT INTO `messages` VALUES('', '$id', '$otherId', '')";
$query_run = mysqli_query($connect, $query);
I have the first column auto_increment thats why I left it empty by writing ''
Now i want this auto_increment value that i have inserted to be inserted in the other table called messages_reply
Do I have to create another query to return it or there is an instant way to insert it here and there?
you have to select the last id on table messages first, then you can insert that last id + 1 into messages reply
$query_sel_last_id = "SELECT id FROM messages ORDER BY id desc LIMIT 1"; // select the last id
after that, you only need to insert to messages_reply, remember to plus the value
$query_sel_last_id + 1
EDIT: gordon's solution is better and simpler, LAST_INSERT_ID()

INSERT INTO two different tables, but have the same ID?

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);

PHP/MySQL INSERT feature logic error

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.

Categories