In the following example, books are grouped using a field called ean
. Use GROUP_CONCAT
combined with GROUP BY
, to get the data concatenated, but separated by any character, in this case use |
... Then, in PHP, by explode
, I can read separately the different books belonging to each ean
. In your case, ean
would equal the company column.
The rest, it would be a matter of adapting the code.
I hope it serves you.
VIEW DEMO
Code:
<?php
require "util/public_db_info.php";
$pdo = new PDO($dsn, $user_name, $pass_word);
echo "<pre>";
/**
* Verificar si hay datos
* Y sacar el contenido usando foreach
* Nótese el uso de count($arrDatos) para contar el total de registros
*/
$sql = "SELECT id, ean, GROUP_CONCAT(title SEPARATOR '|') as libros FROM books WHERE ean=:ean1 OR ean=:ean2 GROUP BY ean;";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":ean1",4);
$stmt->bindValue(":ean2",1);
$stmt ->execute();
$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($arrDatos)
{
echo "SE ENCONTRARON ".count($arrDatos). " REGISTROS AGRUPADOS\n\n";
print_r($arrDatos);
foreach ($arrDatos as $row)
{
echo "\n\nLIBROS CON EL EAN : ".$row["ean"]."\n\n";
//Aquí dividimos los datos usando el separador
$arrLibros=explode("|",$row["libros"]);
foreach ($arrLibros as $libro){
echo $libro."\n";
}
}
}
else
{
echo "No hay datos";
}
echo "</pre>";
$pdo = null;
?>
Result
SE ENCONTRARON 2 REGISTROS AGRUPADOS
Array
(
[0] => Array
(
[id] => 400
[ean] => 1
[libros] => Tú eres el Camino|Cruzando el umbral de la esperanza
)
[1] => Array
(
[id] => 38053
[ean] => 4
[libros] => Hamlet|Romeo y Julieta|Lo que el viento se llevó|No hay amor más grande|El Principito|El Quijote
)
)
LIBROS CON EL EAN : 1
Tú eres el Camino
Cruzando el umbral de la esperanza
LIBROS CON EL EAN : 4
Hamlet
Romeo y Julieta
Lo que el viento se llevó
No hay amor más grande
El Principito
El Quijote