php say some results aren't undifined while some are

Viewed 60

I have a wierd php problem. I get data from mysql with code below

SELECT kitap.kit_id, kitap.kit_adi, yazar.yad as yazar,  
        yayinevi.yeviad as yayinevi,kitap.isbn,kitap.basim_yili, 
        kitap.baski_no,kitap.dil,kitap.cilt,kitap.sayfa, 
        kitap.kategori,kitap.durum
FROM kitap 
    INNER JOIN kitapyayinevi ON kitap.kit_id = kitapyayinevi.kit_id 
    INNER JOIN kitapyazar ON kitap.kit_id = kitapyazar.kit_id 
    INNER JOIN yayinevi ON kitapyayinevi.yevi_id = yayinevi.yevi_id 
    INNER JOIN yazar ON kitapyazar.yazar_id = yazar.yazar_id
SQL;

    $stmt = $connection->query($sql);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    var_dump($result); //This is for debugging purposes

But when I try to print them with code below;

<?php foreach ($result as $item): ?>
    <tr>
        <td class="hide"><?= $item->kit_id; ?></td>
        <td><?= $item->kit_adi; ?></td>
        <td><?= $item->yazar; ?></td>
        <td><?= $item->yayinevi; ?></td>
        <td><?= $item->isbn; ?></td>
        <td><?= $item->baski_no; ?></td>
        <td><?= $item->basim_yili; ?></td>
        <td><?= $item->dil; ?></td>
        <td><?= $item->cilt; ?></td>
        <td><?= $item->sayfa; ?></td>
        <td><?= $item->kategori; ?></td>

It gives me the error below. Everything except $item->yazar and $item->yayinevi print out just fine;

Notice: Undefined property: stdClass::$yazar in C:\Users\Nihal\Documents\KutuphaneYonetim\php\body.php on line 38

Notice: Undefined property: stdClass::$yayinevi in C:\Users\Nihal\Documents\KutuphaneYonetim\php\body.php on line 39

And var_dump($result) prints out like this;

array(1) { [0]=> array(12) { 
                ["kit_id"]=> string(2) "25" 
                ["kit_adi"]=> string(7) "Sınır" 
                ["yazar"]=> string(13) "Beyza Alkoç " 
                ["yayinevi"]=> string(15) "İNDİGO KİTAP" 
                ["isbn"]=> string(10) "6052361580" 
                ["basim_yili"]=> string(4) "2018" 
                ["baski_no"]=> string(1) "4" 
                ["dil"]=> string(8) "TÜRKÇE" 
                ["cilt"]=> string(12) "Karton Kapak" 
                ["sayfa"]=> string(3) "400" 
                ["kategori"]=> string(5) "Roman" 
                ["durum"]=> string(5) "rafta" 
                } 
        }

What would be the problem? can you guys help me find?

2 Answers

You used

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

FETCH_ASSOC so they are all returned as arrays. You are addressing them as if they were objects so for example use

<td><?= $item['yazar']; ?></td>

Alternativley change the fetchAll to

$result = $stmt->fetchAll(PDO::FETCH_OBJ);

and leave the code as you originally had it.

try to convert obj to array so if your value obj or value null that it was not given any error and it's to easy to manage array.

add before your loop.

<?php $result = json_decode(json_encode($result),true); ?>
Related