这是代码
$get_favory = mysql_query("SELECT * FROM favory WHERE user1='$username'");
$values = "";
while($fav = mysql_fetch_assoc($get_favory)) {
$user2 = $fav['user2'];
$values = " OR added_by='".$user2."'";
}
echo $values;
values变量必须如下所示:OR added_by =' zac'或者add_by =' john'或者add_by =' emily'
但我得到了这个结果:OR added_by =' zac'
我必须做什么?
答案 0 :(得分:4)
您每次都要覆盖变量,而不是附加新值。
替换
$values = " OR added_by='".$user2."'";
使用
$values .= " OR added_by='".$user2."'";
不推荐使用mysql_扩展名。你应该使用mysqli_代替。 你的代码应该是:
$connect = mysqli_connect(host,username,password,db_name);
$get_favory = mysqli_query($connect,"SELECT * FROM favory WHERE user1='$username'");
$values = "";
while($fav = mysqli_fetch_assoc($get_favory)) {
$user2 = $fav['user2'];
$values .= " OR added_by='".$user2."'";
}
echo $values;
答案 1 :(得分:0)
使用IN
子句可能更简单:
// you only need user2
$get_favory = mysql_query("SELECT user2 FROM favory WHERE user1='$username'");
while($fav = mysql_fetch_assoc($get_favory)) {
$user2[] = $fav['user2'];
}
$values = "'" . implode("','", $user2) . "'";
echo "SELECT * FROM table WHERE added_by IN ($values)";
您应该移至PDO或至少使用MySQLi扩展程序。