在PHP中爆炸 [英] Exploding in php
问题描述
在我的表用户"中有朋友",
In my table 'users' there are 'friends' ,
喜欢这个:
+----+------+---------+
| id | name | friends |
+----+------+---------+
| 1 | a | 0,1,2 |
| 2 | b | 0,1,3 |
| 3 | c | 0,1 |
+----+------+---------+
我如何使用爆炸功能来获取以逗号(,)分隔的朋友ID(不是0,1,2);
How do I use the explode function to get the friends id one by one (not 0,1,2) that are separated by a comma (,) ;
如何选择ID? (示例):
How do I select the id? (Example) :
$sql = Select id from users where id = (exploded)
if (mysql_num_rows($sql) > 0 ) {
$TPL->addbutton('Unfriend');
}else{
$TPL->addbutton('Add as Friend')
}
推荐答案
此处的解决方案实际上是您的数据库结构稍有更改.我建议您创建一个多对多" 关系表,其中包含用户引用的所有用户朋友.
The solution here is actually a slight change in your database structure. I recommend you create a "many-to-many" relational table containing all of the users friends referenced by user.
+---------+-----------+
| user_id | firend_id |
+---------+-----------+
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 1 |
| 2 | 5 |
+---------+-----------+
如果要在一个字段中存储值列表,则这是数据库设计不是十分理想的第一个迹象.如果您需要搜索一个数值,最好在该字段上放置一个索引以提高效率并使数据库为您服务,而不是反过来:)
If you are storing lists of values within one field then that is the first sign that your database design is not quite optimal. If you need to search for a numerical value, it'll always be better to place an index on that field to increase efficiency and make the database work for you and not the other way around :)
然后要找出用户是否是某人的朋友,您将查询此表-
Then to find out if a user is a friend of someone, you'll query this table -
SELECT * FROM users_friends WHERE
`user_id` = CURRENT_USER AND `friend_id` = OTHER_USER
要获得某个用户的所有朋友,您可以这样做-
To get all the friends of a certain user you would do this -
SELECT * FROM users_friends WHERE `user_id` = CURRENT_USER
这篇关于在PHP中爆炸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!