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.
Related
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'm trying to copy from one table to another table and it works fine, however I also need to insert the current user ID in the new table. I haven't yet figured out how. Normally I would do something like SET user_id = :user_id, but i have never worked with this one.
This is my code:
$q = $conn->prepare("INSERT INTO user_themes(title,code_entry,code_home,code_css,code_category,code_archive)
SELECT title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");
So my question is:
How can I insert user_id (let's say user_id is 1) into the new table as well?
The basis of your query doesn't change. Just add the value to both the columns and `SELECT statement:
INSERT INTO user_themes(user_id, title,code_entry,code_home,code_css,code_category,code_archive)
SELECT :user_id, title, code_entry, code_home, code_css, code_category, code_archive
FROM blogy_themes WHERE id = :id
Then when you execute, bind both :id and :user_id.
From what I understand you want to have the id of the user that is doing the action in all of the new records, you can do something like:
$q = $conn->prepare("INSERT INTO user_themes(user_id,title,code_entry,code_home,code_css,code_category,code_archive)
SELECT '" . (int) $userid ."' as user_id, title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");
This is a workaround in order to keep using the query as it is.
Second option is more "ORM" approach, you can query all the relevant records from the user_themes table, iterate on the result set, clone each row and save it with new user_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);
I am having a problem locating comments for a given user with the following table structure:
usertable (id, userid, name)
comments (id, commentname, date)
Note: usertable.id is not the same as comments.id, and they are both autoincrement
How should I go about updating these tables to fix this problem?
Update
Is this code good for all users get their own votes when someone voted as thilo savage told me ?
$sth = thumbsup::db()->prepare(
'INSERT INTO'
.thumbsup::config('database_table_prefix')
.'votes_users(vid, userid) VALUES (?,?)');
$sth->execute(array($this->vid, $userid));
You've got two options:
Add a 'uid' column to the comments table which references the usertable's 'id' column. That way, you have a way to keep track of which comments belong to which users.
Create a table 'user_comment' with the columns 'uid' and 'cid'. This option leaves the two existing tables as they are, and the 'user_comment' table is responsible for keeping track of which comments belong to which users.
EDIT: Rewritten to use many-to-many relationship because current tables can't be altered.
Create a new table called comments_users with these fields:
cuid (primary key and auto increment) | cid | uid
Then get all of a user's comments with this code:
$user_id = '1234';
// get all the user's comment ids from comments_users table
$find = mysql_query("SELECT `cid` FROM `comments_users` WHERE `uid` = '".$user_id."'");
// generate a query that grabs all those comments
$load = "SELECT * FROM `comments` WHERE ";
while ($row = mysql_fetch_array($find) {
$load .= "`id` = '".$row['cid']."' OR ";
}
// shop off the last OR
$load = substr($load,0,-4);
// put all the user's comments into comments array
$q = mysql_query($load);
while ($comment = mysql_fetch_array($q)) {
$comments[] = $comment
}
print_r($comments);
As far as inserting goes, you'll insert comments into the comments table like you normally would, but then you'd ALSO insert a row into comments_users table filling in the appropriate cid and uid for that comment
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
)