Jordan Vit Jordan Vit - 7 months ago 32
SQL Question

Explode doesn't remove comma from value in database

I have value in database field which has

,
after the name like this
file.pdf,
. I'm tried to remove it with explode but I got error
FPDF error: Unable to find pointer to xref table
when I try to read and generate pdf from this row in database... If I remove manually comma from phpmyadmin everything work perfectly. This is the fragment of the source where I try to explode...

foreach($files as $file) {

$sql = "SELECT file FROM documents WHERE id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $file);
$result->execute();

$resArray = $result->fetchAll();

foreach ( $resArray as $res )
{
$items = explode(',', $res["file"]);

foreach ($items as $item) {

$pdf->addPDF($fileFolder.$item);
}
}
}

Answer

This code doesn't remove a comma, instead it splits the string into multiple parts using the comma as separator. So you effectively get two strings: One with file.pdf and an empty one (because the part after the comma is nothing), and you are iterating over both using foreach, so you are calling addPDF twice, one time with an empty string (which is probably what causes the error).

What you need is this:

foreach ( $resArray as $res )
{
     $pdf->addPDF($fileFolder . rtrim($res["file"], ","));
}

rtrim is used here to explicitely remove trailing characters (here the comma).