我有一个mysql表,其中用户有一个有优势游戏的列。 他们像这样保存:
id username games
1 user1 ,game1, game2, game3
2 user2 ,game2, game4
3 user3 ,game4, game1, game3
现在我想选择至少有一个游戏和我一样的所有用户。
$mygames = ,game2, game5
$statement = $pdo->prepare("SELECT * FROM users WHERE games = ?????");
$statement->execute();
$users = $statement->fetchAll();
它应该给我user1和user2,因为它们都包含game2和我! 我怎么能这样做?
感谢您的帮助:)
答案 0 :(得分:0)
尝试使用Like语句,例如:
for
答案 1 :(得分:0)
我找到了解决方案
$mygames = ,game2, game5
$ug = explode(",", $mygames); //each word is splitted at the ,
$ug = array_filter($ug); //every empty array is deleted
$statement = $pdo->prepare("SELECT * FROM users");
$statement->execute();
$users = $statement->fetchAll();
foreach ($users as $row) {
$usg = explode(",", $row['games']); //each word is splitted at the ,
$usg = array_filter($usg); //every empty array is deleted
$gsame= count(array_intersect($usg, $ug)) > 0; //if a user has at least one game as me it counts(onegame=1, twogames=2 etc...)
if($gsame > 0) { //if gsam is more than 0 it displays the array
<html></html>
}
希望这有助于你们中的一些人:)
答案 2 :(得分:0)
你可以使用正则表达式吗?
select * FROM users where games REGEXP 'game4|game2';
如果您想要包含game4或game2的所有行。
所以你的php需要构建正则表达式。
<?php
$games = ['game2', 'game4']; // an array of the required games
$regexp = implode('|', $games); // converts array to string with pipe as delimiter
echo ($regexp); // outputs 'game2|game4'
所以你的mysql现在变成了
$sql = 'select * FROM users where games REGEXP '. $regexp .';
答案 3 :(得分:-1)
Matt说,使用LIKE语句
更好的&amp;可扩展的方式:
$mygames = ",game2, game5"; // or whatever
// split & trim the gamenames
$games = array_map('trim',split(trim($mygames, ',')));
// for ANY number of games you have, set the condition that selects anyone who have ANY of them.
$statement = $pdo->prepare("SELECT * FROM users WHERE " . substr(str_repeat(" games LIKE ? OR ", count($games)), 0, -3));
$statement->execute();
$users = $statement->fetchAll();