version 2
version 2

Reputation: 1059

Array to string conversion failed in PHP

I have a query which fetches distinct user ids and I am trying to convert it into a comma separated string which I can pass into another sql query having IN in WHERE clause. But I am getting an error saying array to string conversion.

$qry0="SELECT DISTINCT id FROM users  ";
$res0=getData($qry0);
while($row0=mysqli_fetch_array($res0))
{
    $data0      =   $row0['id'];  
}

And I'm trying to convert it as string like this:

$array = explode(",", $data0);

and pass it to another

$qry="SELECT * FROM login WHERE clientid IN(".$array.") ";

Upvotes: 0

Views: 155

Answers (2)

Ranjit Shinde
Ranjit Shinde

Reputation: 1130

The explode() function breaks a string into an array.To break array into string you need to use implode()

$qry0="SELECT DISTINCT id FROM users  ";
$res0=getData($qry0);
$data0 = array();
while($row0=mysqli_fetch_array($res0))
{
    $data0[]      =   $row0['id'];  
}
$array = implode(",", $data0);

Upvotes: 0

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

USe implode instead of explode:

$qry0="SELECT DISTINCT id FROM users  ";
$res0=getData($qry0);
$data0 = array(); // initialize array first
while($row0=mysqli_fetch_array($res0))
{
    $data0[]      =   $row0['id'];  // create array like this
}

$array = implode(",", $data0); // use implode to convert array to string

Upvotes: 1

Related Questions