Insert list id and item - php

I'm a bit lost and cant find anything to guide me in the right direction so maybe some of you got a suggestion. Im trying to do add items in a list.
First of all I have a user table which contains the users id. This id is put as a session so when the user creates adds a list their id is inserted in the list table, so I know which user the list belolngs to. The list table aslo contains a listname and an unique id which is gained from auto increment.
List:
id(from user) ai Listname
1 1 List one
1 2 List two
3 3 List one
My next table is to add items in the list. It contains the ai from list, and its own auto increment and the name on the item.
ai(from list) itemAi itemName
? ? ?
What I dont get is to insert it. Lets say I created a list a its in my table and I insert an item name and itemAi gets automaticly set, how do I set which list I'm currently in? Do i set it as a session or what's the normal approach?
Update:
$name = 'Test';
$sql = $con->prepare('INSERT INTO list (name) VALUES (?)');
$sql->bind_param("s",$name);
$sql->execute();
$sql->close();
$user = $_SESSION['user_id'];
$qq = $con->prepare('INSERT INTO user_list (user_id, list_id) VALUES (?,?)');
$qq->bind_param("ss", $user,????);
$qq->execute();
$qq->close();
$con->close();

I'd try to normalize your tables into logical concepts: user, list, item etc. Then, use join tables to create the many-to-many relationships between them.
Tables:
user: id (auto-increment), first name, last name, ...
list: id (auto-increment), name
item: id (auto-increment), name
user_list: user_id (FK to user.id), list_id (FK to list.id)
user_list_item: user_id (FK to user.id), list_id (FK to list.id), item_id (FK to item.id)
*FK = foreign key. There are ways to shorten this up a bit, but I'd go for the explicit structure here to keep things clean and separated.
Then, in PHP you keep track of your user and the list they're currently working on in the session.
<?php
// After logging in
$_SESSION['user_id'] = ...;
// Choose which list the user is working on
$_SESSION['list_id'] = ...;
If they haven't chosen a list to work with, force them to. This is part of the validation.
Now every time the user wants to make changes, use those session values.
Your business logic would be:
<?php
// Associate a list with a user
INSERT INTO `user_list` (user_id, list_id) VALUES (?, ?)
?: $_SESSION['user_id']
?: $_SESSION['list_id']
// Disassociate a list from a user
DELETE FROM `user_list` WHERE user_id = ? AND list_id = ?
?: $_SESSION['user_id']
?: $_SESSION['list_id']
// Insert a new item into a user's list
$itemId = INSERT INTO `item` (name) VALUES (?)
?: 'Bread'
INSERT INTO `user_list_item` (user_id, list_id, item_id) VALUES (?, ?, ?)
?: $_SESSION['user_id']
?: $_SESSION['list_id']
?: $itemId
// Clear our the items from a specific list
DELETE FROM `user_list_item` WHERE user_id = ? AND list_id = ?
?: $_SESSION['user_id']
?: $_SESSION['list_id']
// Empty all items for a given user, but keep the lists intact.
DELETE FROM `user_list_item` WHERE user_id = ?
?: $_SESSION['user_id']
// Remove a specific item from a user's list
DELETE FROM `user_list_item` WHERE user_id = ? AND list_id = ? AND item_id = ?
?: $_SESSION['user_id']
?: $_SESSION['list_id']
?: $itemId
Lets say the user inserts a new list and I insert its name and an id
on the list gets A.i. Then at the same time I have to insert the
session user_id and the list_id in user_list, the user id is set from
session, but how do I get the list_id on the new created list?
Good question. Most RDBMs give you a function to get the last inserted ID. PDO specifically exposes it via lastInsertId.
In this case, you'd issue 2 insert statements. The first one will create the new list and the second will associate the list with the user by grabbing the ID of the newly created list and the current user ID from the session.
<?php
// Create a new list and assign it to a user
// The form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Connection to your DB.
// See https://phpdelusions.net/pdo#dsn for a decent tutorial on PDO.
$pdo = new PDO(...);
// Get the name from the submitted form
$listName = $_POST['name'];
// Create the list and get the ID of the newly created list.
$stmt = $pdo->prepare('INSERT INTO `list` (name) VALUES (?)');
$stmt->execute([$listName]);
$listId = $pdo->lastInsertId();
// Now, associate the new list with the user.
$stmt = $pdo->prepare('INSERT INTO `user_list` (user_id, list_id) VALUES (?, ?)');
$stmt->execute([$_SESSION['user_id'], $listId]);
}

Related

How to insert data to another table by id

I want to complete user sign up.
firstly user will write username and password, table called users, I have id as primary key.
secondly user will write address, phone number and zipcode, table called userdata, I have userid as index(key).
I have did a relation between id from table user and userid from table userdata.
So now I want to insert data from php code I did two forms one for user and it has two input for username and password it works well and data inserted.
in the second form I have select option has id from table users and it works well.
then in the same form I have three inputs phone number, address and zipcode.
so the question is how I can insert the data to userdata by the same to the same id. so userid in table user will be the same id in table userdata.
I need sql code.
I used that :
"INSERT INTO userdata(address, phone, zipcode) VALUE (:address, :phone, :zip) SELECT 'id' FROM 'users';"
First :
$q = "NSERT INTO users(username, password) VALUE ('Adam', '12345678')";
$r = $connect->query($q);
//get the last id u inserted
$last_id = mysqli_insert_id($connect);
Second :
$q = "NSERT INTO userdata(address, phone, zipcode,user_id) VALUE ('California', '12345678', '1111','$last_id')";
$r = $connect->query($q);
and if you want to make the (id) not the (userid) the same just :
$q = "NSERT INTO userdata(id, address, phone, zipcode) VALUE ('$last_id','California', '12345678', '1111')";
$r = $connect->query($q);

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.

how to remove data duplicacy in customer table

i have a table customer_stock_entries.. i want to insert the item if the item and supplier is not available and i want to update the item if item and supplier is available
Example in my table i have stock_supplier_name and quantity. What i want to do is that if the stock supplier name entry is new then insert it into the table and if the entry is already there then delete the previous value in column 'quantity' and insert the new value.
i am stuck with this. Please help me out
I have tried something like this.
for ($i = 0; $i < count($stock_name); $i++) {
$count = $db->countOf("customer_stock", "name='$stock_name[$i]'");
if ($count == 0) {
$db->query("insert into customer_stock(name,quantity) values('$stock_name[$i]',$quty[$i])");
echo "<br><font color=green size=+1 >New Stock Entry Inserted !</font>";
$db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price) values('$autoid','$stock_name[$i]',0,'$supplier','$cost[$i]','$sell[$i]')");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name, stock_supplier_name, quantity, company_price, selling_price, opening_stock, closing_stock, date, username, type, total, payment, balance, mode, description, due, subtotal,count1,billnumber) VALUES ( '$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]',0,'$quty[$i]','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
} else if ($count == 1) {
$amount = $db->queryUniqueValue("SELECT quantity FROM customer_stock WHERE name='$stock_name[$i]'");
$amount1 = $amount + $quty[$i];
$db->execute("UPDATE customer_stock SET quantity='$amount' WHERE name='$stock_name[$i]'");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name,stock_supplier_name,quantity,company_price,selling_price,opening_stock,closing_stock,date,username,type,total,payment,balance,mode,description,due,subtotal,count1,billnumber) VALUES ('$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]','$amount','$amount1','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
Thanks
Typical solution to this problem involve following typical steps:
Check if the record for the stock supplier exists by using a select query and if it exists, update the quantity attribute.
If the the record doesn't exist, then insert the record in the table.
Sample Code as requested:
IF EXISTS(SELECT * FROM Users WHERE UserId = #UserId)
BEGIN
UPDATE TC_Users SET Salary = 25000 WHERE UserId = #UserId
END
ELSE
BEGIN
INSERT INTO TC_Users(UserId, Salary) VALUES(#UserId, 25000)
END
Hope this helps you.
Hare are some information's regarding your problem:
Primary Keys (To Avoid Duplication Of Data) :
Always use primary keys in your Database Table Structure i.e consider one column as primary key in order for it to be unique so that duplicate value won't be able to be inserted in your records.
Example : For instance I have a table with following columns as id,username,password,name .Now in order for to avoid duplication of data i.e that I don't want people to register with same username which means that username column value should be unique so instead I mark my username column as Primary Key.So now the new upcoming members won't be able to register with the same username which is already available in database i.e someone already registered using that username.Instead they will be needed to register with unique username.
Solution :
While here is code for to update your quantity value if supplier is already present in the database and if not so then insert the new record..!
$supplier_name = $_POST['supplier];
$query = mysqli_query($mysqli,"SELECT * FROM table");
$results = mysqli_fetch_array($query);
for ($i=0;$i<=count($results);$i++) {
//IF supplier is available in database
if ($results[$i]['supplier'] == $supplier_name) {
$query = mysqli_query($mysqli,"UPDATE table SET quantity=$quanity_new_value WHERE supplier=$supplier_name");
} else {
// If supplier is not available in database so it will insert new record
$query = mysqli_query($mysqli,"INSERT INTO table (supplier, quanity, email) VALUES ($supplier_name, $quantity, $email)");
}
}

Issue with copying from one MySQL table to another

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.

insert data from one table to another table

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

Categories