Home > Software design >  Resolve php error : Trying to access array offset on value of type bool
Resolve php error : Trying to access array offset on value of type bool

Time:05-11

I'm trying to insert SQL response into .csv file, but when I execute my code, I got this error : Trying to access array offset on value of type bool

This is my code :

$fh = fopen("file.csv", "w");
if($fh === false) { exit("Failed to create CSV");}
$stmt = $db -> prepare("(SELECT DISTINCT nomperso.nom as perso1, rel.relation as relation, GROUP_CONCAT(np.nom) AS perso2, rel.id as idnat, rp.id_personnage as id_perso1, rp.id_maitre_eleve as id_perso2
from rel_perso_maitres_eleves rp
LEFT JOIN noms_personnages nomperso
ON nomperso.id_personnage=rp.id_personnage
INNER JOIN personnages_relations rel
ON rp.id_nature_relation=rel.id
RIGHT JOIN noms_personnages np
on np.id_personnage=rp.id_maitre_eleve
where nomperso.nom like '$nom' and rel.id_langue like '4' GROUP BY np.id_personnage order by relation ASC)
UNION
(SELECT DISTINCT nomperso.nom as perso1, rel.relation as relation, GROUP_CONCAT(np.nom) AS perso2, rel.id as idnat, rp.id_personnage as id_perso1, rp.id_autre_perso as id_perso2
from rel_perso_autres_relations rp
LEFT JOIN noms_personnages nomperso
ON nomperso.id_personnage=rp.id_personnage
INNER JOIN personnages_relations rel
ON rp.id_nature_relation=rel.id
RIGHT JOIN noms_personnages np
on np.id_personnage=rp.id_autre_perso
where nomperso.nom like '$nom' and rel.id_langue like '4' GROUP BY np.id_personnage order by relation ASC)");
$stmt -> execute();
while($row = $stmt -> fetch()){
    fputcsv($fh, [
        $row['nomperso.nom'].".". $row['rel.relation'].".". $row['nomperso.perso2'].","
    ]);
    var_dump($row['perso1']);
}
fclose($fh);

Can you help me ? Thanks a lot.

CodePudding user response:

mysqli_stmt::fetch doesn't return a row of result, you need bind columns to variables first.

$stmt->bind_result($perso1, $relation, $perso2, $idnat, $id_perso1, $id_perso2);

Then each time you fetch a row, these variables will be filled with data.

while($stmt->fetch()){
    fputcsv($fh, [$perso1.".". $relation.".". $perso2.","]);
    var_dump($perso1);
}
  •  Tags:  
  • php
  • Related