2014-09-30 60 views
0

我可能会遇到错误的方向,但我想从数据库中获取数据数组,然后在另一个SQL语句中使用该数组。如何在sql语句中使用sql数据库中的数组

这里是我当前的代码:

$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; 
    } 

我得到的错误:

syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

不知道有没有什么帮助。

任何建议将是非常有帮助的,因为我一直坚持这个年龄!第一,而不是每个quering他们

$array = $idFriend . ','; //There should be a period here. 
+0

你在同一个数据库中查询的两张表是?这看起来应该是一个带JOIN的单个查询,而不是围绕构建数组和执行多个查询。另外,第二个查询是否应该在* while循环中? – 2014-09-30 14:55:30

+0

你能告诉我们'$ query_friend_club_count'是什么吗? – 2014-09-30 14:58:06

+1

请[不要在新代码中使用'mysql_ *'函数](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。 *他们不再维护,并[已正式弃用](https://wiki.php.net/rfc/mysql_deprecation)*。看到[红色框](http://uk.php.net/manual/en/function.mysql-connect.php)?学习[准备的语句](http://en.wikipedia.org/wiki/Prepared_statement),并使用[PDO](http://us1.php.net/pdo)或[MySQLi](http:// us1.php.net/mysqli)。 [这篇文章](http://php.net/manual/en/mysqlinfo.api.choosing.php)将帮助你决定哪些。 – 2014-09-30 14:59:39

回答

0

你犯了一个小错误

$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; 

或者,如果此列是一个INT,无需报价:

$array = implode(', ', $array); 
+0

仍然会出错。在最后一个字之后不应该有逗号。在查询之前,您可能需要修剪您的字符串。 – 2014-09-30 14:56:49

+0

这是许多错误之一,语法和逻辑。指出只是这个错误不会帮助 – Steve 2014-09-30 14:56:55

+0

感谢您的回复!它现在有点类似四个1秒的数字最好的方法来计数? – Jordanbaggs 2014-09-30 14:57:19

4

您也可以将它们:

+1

很好的答案。值得注意的是,如果ID不是数字,则数组中的值应该被转义。复杂的注入攻击可以使用转义进入数据库的输入,然后利用这样的查询。或者,如果无辜值包含字符串分隔符,则可能会导致错误。 – 2014-09-30 15:00:23

+0

@MitchSatchwell是的,这也是一个很好的见解 – Ghost 2014-09-30 15:08:57

0

正确的方法是:

$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))"; 
相关问题