2016-03-28 34 views
0

我使用下面的代碼傳遞數組值到MySQL查詢,但數組字符串轉換錯誤會陣列串皈依錯誤在PHP

$sql =mysql_query("SELECT userId from groupmembers where groupId='$groupId'"); 
$bjson = array(); 
$i = 0; 
while($result=mysql_fetch_assoc($sql)) 
{ 
    $bjson[$i]['userId'] = $result['userId']; 

    $i++; 
} 

$query = "SELECT firstName 
    FROM users 
    WHERE userId IN('" . implode("','", $bjson) ."')"; 
+0

[你的腳本是在對SQL注入攻擊的風險。(http://stackoverflow.com/questions/60174/how-可以防止SQL注入在PHP) –

+0

請[停止使用'mysql_ *'功能](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-在-PHP)。 [這些擴展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中刪除。瞭解[編寫]​​(http://en.wikipedia.org/ wiki/Prepared_statement)語句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli.quickstart .prepared-statements.php)並考慮使用PDO,[這真的很簡單](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

該死的棄用和刪除功能了! – rray

回答

6

無需兩個查詢和循環的只是使用

SELECT firstName 
    FROM users 
    WHERE userId IN(SELECT userId from groupmembers where groupId='$groupId') 

注: - MySQL是不推薦改爲使用庫MySQLi或PDO

閱讀How can I prevent SQL injection in PHP?

+0

謝謝你的工作 –

+0

找你!歡迎 – Saty

1

可以使用查詢聯接,以節省循環

SELECT u.firstName FROM users u JOIN groupmembers gm ON gm.userID = u.userID WHERE gm.groupID='$groupId'