Search code examples
phpmysqlexplodeimplode

PHP implode not add all values of database


I am in trouble and need your help.

array conversion into string only adds the last row values in implode not all.

I have following values in mysql database

Table Name: Item1

ID     Value
01     James,Jenny,Loreal
02     Sunny,John,Razil

now i want to call values from another table where names not equals to the above values. I used below query.

$stmt= $db->prepare("Select * from Item1");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_BOTH))
{
   $mark=explode(',', $row['Value']);
}

 $string_version = "'" . implode("','", $mark) . "'";

//in $string_version it only ads the 2nd row values not all rows values i need to add the all values which is in Values colunm

$stmt = $db->prepare("Select * from item2 where names not in (".$string_version.") ");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_BOTH))
{
echo $row['name'];
}

result:

James
Jenny
Loreal
Peter

result expected:

Peter

Solution

  • I would follow a different path (use an array to hold all names):

    $stmt= $db->prepare("Select * from Item1");
    $stmt->execute();
    $names = [];
    while($row = $stmt->fetch(PDO::FETCH_BOTH))
    {
       $mark=explode(',', $row['Value']);
       foreach ($mark as $name)
         $names[] = "'".$name."'";
    }
    
    $stmt = $db->prepare("Select * from item2 where names not in (".implode(', ', $names).") ");
    $stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_BOTH))
    {
        echo $row['name'];
    }
    

    Please beware this method would not work if a name contains apostrophe character ('). Use escaping supported by your database layer.