So I've been trying to create a simple friend system. When you register, you get randomized numbers and chars of 8 in length. I save this number in a column to the user. I have been trying to insert the currently sessioned user(PHP), $SessionUser together with the friends' username, uidUsers using an "INSERT SELECT WHERE" statement, but something goes wrong. Heres something I have tried:
$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2)
values($sessionUser, (SELECT uidUsers FROM users WHERE idFriendCode = $idFriendCode)");
Inside the table, friends, I have two columns, uid1 (the sessioned user/sender) and uid2 (the reciever, name of specified $idFriendCode). I want to insert the $sessionUser to the uid1 and whatever username (uidUsers) that matches with the $idFriendCode to the uid2. This does not seem to work and I don't know why. I imagine the problem is that I can't use a PHP variable like this.
I know that I don't use prepared statements. I have tried to implement it, but I think it's much harder than just using a basic mysqli_query().
You may phrase your insert as an INSERT INTO ... SELECT:
INSERT into friends (uid1, uid2)
SELECT $sessionUser, uidUsers
FROM users
WHERE idFriendCode = $idFriendCode;
Note that you should ideally be using a prepared statement here, so the above should look like:
INSERT into friends (uid1, uid2)
SELECT ?, uidUsers
FROM users
WHERE idFriendCode = ?;
Try having a new variable for select and use it in the insert query
example:
$select_qr='SELECT uidUsers FROM users WHERE idFriendCode = $idFriendCode'
$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2)
values($sessionUser, $select_qr)");
Related
I am trying to design a very simple table that stores the data of friends in a community.
Therefor I store the userId of 2 friends respectively.
Goal
User wants to load his/her friends list.
t_friends Option 1:
Query
SELECT * FROM t_friend WHRE user_id = 10
10 is the current userId of the user which is looking for his friends list and he has 1 friend userId(20)
This way userId (10) finds his friend (20) BUT what if userId(20) were looking for his friends?
The query is coupled with userId.
That leads me to another design that contains redundant data:
t_friends option 2:
userId (10) loads now:
SELECT * FROM t_friend WHRE user_id=10
Similiar to that the query for userId(20) would then be:
SELECT * FROM t_friend WHRE user_id=20
But what about the redundancy? That leads me then to that query using table design option 1:
SELECT * FROM t_friend WHERE user_id=10 OR friend_id=10
I have a feeling that there is a smarter way to solve that. Do You have any experiences with that structure?
Thanks
Add field friendship_key:
ALTER TABLE t_friend ADD friendship_key decimal(22,11);
CREATE UNIQUE INDEX friendship_key_unique ON t_friend (friendship_key);
And php part:
$friends = [$userId, $friendId];
$key = min($friends).'.'.max($friends);
$q = "SELECT * FROM t_friend WHERE friendship_key = ".$key;
insert:
$friends = [$userId, $friendId];
$key = min($friends).'.'.max($friends);
$q = "INSERT INTO t_friend (friendship_key, userId, friendId) VALUES (".implode(',', [$key, $userId, $friendId]).")";
Instead of using VARCHAR for friendship key I've used decimal to minimize data for relation key.
To keep it simple just create functions:
function insertFriendship($user1, $user2) {
$key = min([$user1, $user2]).'.'.max([$user1, $user2]);
$q = "INSERT INTO t_friend (friendship_key, userId, friendId) VALUES (".implode(',', [$key, $user1, $user2]).")";
mysql_query($q);
}
function getFriendsOf($user) {
$q = "SELECT * FROM t_friends WHERE ".$user." IN (userId, friendId)";
return mysql_query($q);
}
function areFriends($user1, $user2) {
$key = min([$user1, $user2]).'.'.max([$user1, $user2]);
$q = "SELECT 1 FROM t_friends WHERE friendship_key = ".$key." LIMIT 1";
$q = mysql_query($q);
return (mysql_num_rows($q)>0);
}
I think this is the only way to store data about the relationships. When you are storing the relationship try to store the min value as the userId and max value as the friendId. make both values altogether unique and you will not get any duplicate values. When you search for users use something like below
SELECT * FROM t_friend WHERE user_id=10 OR friend_id=10
You may want to use the following query which verify if your user is not already a friend of another first :
INSERT INTO t_friend (userId, friendId)
SELECT 10, 20
WHERE NOT EXISTS ( SELECT userId
FROM t_friend
WHERE userId = 20
AND friendId = 10)
Thanks to this (french) topic about redundancy verification here.
I have a SQL Query, although it is executing, but how should i verify if it is giving me the desired result.
For example: My query
$query3 = "SELECT COUNT(DISTINCT(uid)) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
In the above query i am trying to count the number of distinct user ID's(uid) from the table named user-infowhere date is 2011-10-10.
How should i display the count which is calculated for the given date?.I need to know it and perform some further operations on it!
$query3 = "SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
$result = mysql_query($query3);
$row = mysql_fetch_array($result);
echo $row['num'];
Just do:
SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'
This SO post goes into some details about how count and count(distinct ...) work. With just count, there is a hidden/assumed function of count(all ... ) actually happening (it's just the default value). If you want to only count distinct things, switch it to the non-default and do the count(distinct ...) instead. I didn't know it existed for my first 6 months of writing sql or so...
You can set a variable sing the result...
SET #userVar=SELECT
COUNT(DISTINCT uid)
FROM
user_info
WHERE
DATE(starttime)='2011-10-10';
Then you can use that variable in your next operation or query.
Hi I am creating an array of user id's with a query. With another query I would like to select from a given table where the user_id is one that is in the array created from my very first query. How can I use an array in my WHERE clause?
Just for reference: $row_interest is the array
My Code:
//Grabs the user id's of the users that have the queried interest
$interest_search_query= "SELECT DISTINCT user_id FROM interests WHERE interest LIKE
'%".$search_term."%'";
$interest_search_result= mysqli_query($connect, $interest_search_query);
$row_interest= mysqli_fetch_array($interest_search_result);
//Grabs the user information with each user id
$search_query= "SELECT DISTINCT user_id, fname, lname, profile_pic, school FROM users
WHERE user_id IN $row_interest";
I tried "WHERE user_id IN $row_interest", but it doesn't seem to work. What could I be doing wrong?
Thanks.
$search_query= "SELECT DISTINCT user_id, fname, lname, profile_pic, school FROM users
WHERE user_id IN (".implode(',',$row_interest).")";
You can actually merge both queries.
SELECT distinct user_id, fname, lname, profile_pic, school
FROM users
WHERE user_id in
(SELECT distinct user_id from interests
where interest like %{search_term}%)
You could build an IN() clause for your SQL in PHP, but since the set is coming from another query you could use a JOIN to do this.
Edit:
I can't test this without your data, but the join would be something like
$search_query= "SELECT DISTINCT u.user_id, u.fname, u.lname, u.profile_pic, u.school
FROM user u
INNER JOIN interests i ON u.user_id = i.user_id
WHERE i.interest like '%".$search_term."%'";
It sounds like you could just use a join, but $row_interest is an array, and it is interpolated as "Array" in the query. It seems like you want to build the entire array first
$rows = array();
while ($row = mysqli_fetch_array($interest_search_result)) {
$rows[] = $row['user_id'];
}
Then you can create the "IN" clause you need.
"WHERE user ID IN (" . implode(",", $rows) . ")"
Your code is vulnerable to injection. You should properly parameterize the queries using prepared statements. This is more difficult to do with a variable number of arguments in mysqli as I understand it, but it is something to keep in mind.
My users can search for an order by an address right now. What I would like to do is let them be able to search with multiple criteria. Let them search by address, city, state, etc etc.
I have tried using the following code, but it doesn't seem to work.
$sql = ("SELECT order_number, sitestreet FROM `PropertyInfo` WHERE `sitestreet` LIKE '%$street%' OR `sitecity` LIKE '%$city%' AND `user` LIKE '$user'");
$result = mysql_query($sql);
I don't think it's reading the value in $user cause it displays all orders for all users.
How can I make it possible to search for an order using multiple serach values?
Thank you!
Wrap your OR statements in parenthesis so it forms one top-level condition, the user is the other top-level condition:
$sql = '
SELECT
`order_number`,
`sitestreet`
FROM
`PropertyInfo`
WHERE
(
`sitestreet` LIKE "%'.$street.'%" OR
`sitecity` LIKE "%'.$city.'%"
) AND
`user` = '.$user;
Also note, you want a direct match to the user column, use = instead of LIKE. I am assuming that $user is a numeric ID...
How about trying like
$sql = ("SELECT order_number, sitestreet FROM PropertyInfo WHERE (sitestreet LIKE
'%$street%' OR sitecity LIKE '%$city%') AND user LIKE '$user'");
AND has a higher order of precedence than OR (see http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html for details). You need to wrap your OR statement in parentheses so it get evaluated as one statement, before the AND statement.
SELECT order_number, sitestreet
FROM `PropertyInfo`
WHERE (`sitestreet` LIKE '%$street%' OR `sitecity` LIKE '%$city%')
AND `user` LIKE '$user'
Try:
$sql = ("
SELECT order_number, sitestreet
FROM `PropertyInfo`
WHERE (`sitestreet` LIKE '%$street%'
OR `sitecity` LIKE '%$city%')
AND `user` LIKE '$user'");
You should group the ORs together. The way it is written I believe it is reading it as 'if Street matches, ignore any other conditions (OR), otherwise both city and user must match.
Also G molvi's point is good, unless you're looking for a pattern match, go with =
HTH
basically this is on the end of a dynamic form where the user can add multiple users of however many they want to a group, so i storte all the inputs in an array user[].
I want to query the array values and gain the userid for each then run another query with the user ids, inserting the userids into another table.
I am a beginner so I am getting lost in this. I looked at trying to use a for each method but couldnt get that working so now im trying a while.
here is my code ive been playing around with, i imagine its completely wrong :(
$query = 'SELECT * FROM users_tb WHERE student_number IN('.implode(',', $array).')';
mysql_query($query) or die(mysql_error());
$result=mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) VALUES('$group','$row['user_id']')";
mysql_query($sql) or die(mysql_error());
mysql_close();
}
please help? :D
regards
You want to use INSERT SELECT:
INSERT INTO group_association (group_id, user_id)
SELECT ' . $group_id . ', user_id
FROM users_tb WHERE student_number IN('.implode(',', $array).')
You have some extra quotes in the INSERT query, it should look like this:
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) ".
"VALUES('$group','$row[user_id]')";
Other than that, it looks like it should work if $group is a group id.