简体   繁体   中英

MySQL query Question?

I'm trying to stop members from adding them selves as a friend but I can't seem to get it to work the last line of code in my MySQL query AND '$user_id' <> '$friend_id' is trying to check if the user id is the same as the friend id and if so stop running the query but for some reason the code will still run.

How do I fix this so the query stops running when the user tries to add themselves as a friend?

Here is the MySQL query.

 SELECT *
 FROM friends
 WHERE user_id = '$user_id'
 AND friend_id = '$friend_id'
 AND '$user_id' <> '$friend_id'

Here is the MySQL table.

CREATE TABLE friends (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
friend_id INT UNSIGNED NOT NULL,
PRIMARY KEY (id),
);

Why you can not do this as simple as this..

You would have a form of course which is submitting the userID and the friendID. for example the form submitted values are ..

$user_id;
$friend_id;

Then, why can not you compare

if($user_id == $friend_id) {
   //user has selected himself as friend
}
else {
   // different user has been selected as friend
}

If I am right, also in the form you can restrict by not displaying own ID to select as friend.

any comments?

 "SELECT *
 FROM friends
 WHERE user_id =" . '$user_id' .
 " AND friend_id = " . '$friend_id' . 
 " AND user_id <> friend_id";

should work (assuming you are useing PHP).

What do you want to archive with your select query?

At the moment it seems like you want to display all friends of a user. If that's the case than you should prevent an user from adding himself as a friend sooner. Check whether it's a legit friend when you are doing your insert statement.

That way you don't have bad data in your database and you save database resources because the database doesn't have to check every time you display the friends.

The SELECT query is not where you need to work to stop users adding themselve as friends. You should have an INSERT statement somewhere in your code and it is on it you have to work. You can simply test if $user_id == $friend_id and not issue the INSERT statement if true.

You will also need to "clean" your existing friends table with:

DELETE FROM friends WHERE user_id = friend_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM