[英]How do I use an array from an sql database in an sql statement
I'm probably going in the complete wrong direction but I want to get an array of data from the database and then use that array in another SQL statement. 我可能会朝完全错误的方向前进,但是我想从数据库中获取数据数组,然后在另一个SQL语句中使用该数组。
Here is my current code: 这是我当前的代码:
$result = mysql_query($query_friend_club_count) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$row['idPerson']. " - ". $row['idFriend'];
$idFriend = $row['idFriend'];
$array = $idFriend',';
$query_friends = "SELECT * FROM whosout WHERE idPerson IN ('$array')";
$query_friends_run = mysql_query($query_friends);
$friendCounter = mysql_num_rows($query_friends_run);
echo $friendCounter;
}
I'm getting a error of: 我收到以下错误消息:
syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
语法错误,意外T_CONSTANT_ENCAPSED_STRING
Don't know if that helps. 不知道这是否有帮助。
Any suggestions would be really helpful as I've been stuck on this for ages!! 任何建议都会非常有帮助,因为我已经坚持了很长时间!
You can also group them first instead of quering them each: 您也可以先对它们进行分组,而不用对每个分组进行查询:
$array = array();
while($row = mysql_fetch_array($result)){
$array[] = mysql_escape_string($row['idFriend']); // escape just to be sure
}
$array = "'".implode("','", $array) . "'"; // comma separated values
$query_friends = "SELECT * FROM whosout WHERE idPerson IN ($array)";
$query_friends_run = mysql_query($query_friends);
$friendCounter = mysql_num_rows($query_friends_run);
echo $friendCounter;
Or if this column is an INT, no need for quotes: 或者,如果此列是INT,则不需要引号:
$array = implode(', ', $array);
您犯了一个小错误:
$array = $idFriend . ','; //There should be a period here.
Correct way is: 正确的方法是:
$arr = array();
while($row = mysql_fetch_array($result)){
$idFriend = $row['idFriend'];
$array[] = $idFriend;
}
// then implode that array using IN sql statement.
$query_friends = "SELECT * FROM whosout WHERE idPerson IN (implode(','$arr))";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.