0

I am using the following code for passing the array value into mysql query but array to string conversion error will come

$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) ."')";
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
A.C.Manikandan
  • 227
  • 2
  • 3
  • 12
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Mar 28 '16 at 12:24
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 28 '16 at 12:24
  • Damn deprecated & removed functions again! – rray Mar 28 '16 at 12:25
  • Try: `$bjson[$i] = $result['userId'];` – Akhil VL Mar 28 '16 at 12:28

2 Answers2

6

No need of two query and loop just use

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

Note:- mysql is deprecated instead use mysqli or PDO

Read How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Saty
  • 22,443
  • 7
  • 33
  • 51
1

Can use a join in your query to save the loop

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