I'm trying to do a MySQL Query that adds information to a database in a format that doesn't overwrite it's current value, but instead appends it as in the friends column would have friend1, friend 2, friend 3 ... etc.
First I am unsure if INSERT INTO is right:
$username = $_SESSION['username'];
mysql_query("INSERT INTO members (friends) WHERE username = $username
VALUES ('$friendtoadd')");
What I want to do is have this do two things
1) Add the friend in a format mentioned so that it can later be called out that if the $username set in session is active then the results posted on the page are only from those other users contained in their friends column.
2) If the $friendtoadd already exists in their column for friends then it does nothing.
UPDATE members SET friends = CONCAT_WS(', ', friends, '$friendtoadd') where username = '$username'
I hope $friendtoadd as well as $username are sanitized through mysql_real_escape_string
Also, this design isn't very good. You should have a seperate friends table
so
table friend
id (auto increment), userID, name)
then do
Insert into friend SET userID = $userID, name = '$friendName'
Related
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]);
}
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);
I am trying to create a table that logs steps depending on date and the user id. But when I run my code, it happens that I get duplicate rows if a user logs their steps several times a day. I can't have a date with a unique key because that would cause all other users unable to log steps if a any other user has logged steps the same day. So my point is that I want to remove the option of having duplicate rows where user id and date is identical. I have two tables
Table a and table b, and I will refer to them as something.a and something.b
I have a problem with returning a valid row when using $entry = "SELECT * FROM table.a WHERE userid.a = '$user_id.b' AND date=NOW()"
I want to use it as a conditional to decide to either UPDATE or INSERT INTO table.a. I have user_id.b from an previous query which works as it is, so I will leave that as it is for now.
Here is how I query the database:
$entry_result = mysqli_query($conn, $entry);
Which is used here:
if (mysqli_num_rows($entry_result) > 0){
$conn->query("UPDATE steplogger SET steps='$steps' WHERE userid='$user_id' AND date=NOW()");
} else {
$conn->query("UPDATE users SET totalsteps = totalsteps + ('$steps') WHERE username = '$user'");
$conn->query("INSERT INTO steplogger (steps, userid, date) VALUES ('$steps', '$user_id', NOW())");
}
Any thoughts on what I am doing wrong?
PS. When I echo $entry_result I get a mysqli object.
As you said :
I want to remove the option of having duplicate rows where user id and date
The best way is to create an UNIQUE index on user_id and date, this way you won't be able to insert two rows with same user_id and date.
With an UNIQUE index, you can use INSERT...ON DUPLICATE KEY UPDATE that will do what you want : you will insert a new row (new user_id + date) and if a row already exists with the same user_id and date, you will update the row.
Here is the documentation : https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
You can try like this
if (mysqli_num_rows($entry_result) > 0){
$conn->query("UPDATE steplogger SET steps='$steps' WHERE userid='$user_id' AND date=".NOW().")";
} else {
$conn->query("UPDATE users SET totalsteps = totalsteps + ('$steps') WHERE username = '$user'");
$conn->query("INSERT INTO steplogger (steps, userid, date) VALUES ('$steps', '$user_id', ".NOW()."))";
}
To get current date in NOW() function, you can use this function.
And also format of the two conditions should be same.
My table looks like this:
check_in_id | amount | date | user_id (foreign key of user table )
In the interface it asks user to enter amount, date, username, password. When running the insert into query, how do I get user_id from that user table to insert into this table?
I suppose you have one main table (say: tbl_login ) to store username, password, user_id (primary key).
So, You first retrieve user_id with username and password like:
SELECT user_id FROM tbl_login WHERE username = '$username' AND password = 'password';
Where $username and $password is your entered username and password from interface.
So after getting user_id , now you have all needed values, so you can easily insert these in your given table.
Since the information in you query is incomplete, I will try to give an answer with certain assumptions.
check_in_id: an auto increment id in
You want to insert into table only if username and password matches.
The variables with '$' are the user inputs
insert into <your table>
(check_in_id, amount, date, user_id)
select null, $amount, $date, user_id from user
where username = $username and password = $password
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