简体   繁体   中英

php pdo oop fetch data not working

Class PHP

<?php

    class product extends db {

        function viewCat(){

            $dbcon = new db();
            $connn = $dbcon->dbcon();

            try {
                $stmt = $connn->prepare("SELECT * FROM `cat`");

                $resultcat = $stmt->execute();

                return $resultcat;

            } catch (PDOException $e) {
                echo 'Error: ' . $e->getMessage();
            }

        }  

    }

    ?>

the view

<?php
$menu = new product();

$resultmenux = $menu->viewCat();


    foreach ($resultcatx as $row) {
        print_r($row);
    }

?>

the error i get is

Warning: Invalid argument supplied for foreach()

It should be like this:

$resultmenux = $menu->viewCat();


foreach ($resultmenux as $row) {
    print_r($row);
}

in your class file it should be, as I commented you are not fetching the data

$stmt = $connn->prepare("SELECT * FROM `cat`");

$stmt->execute();

$resultcat = $stml->fetchAll(PDO::FETCH_ASSOC); // this line was missing

return $resultcat;

and in view file as answered by shankhan

$resultmenux = $menu->viewCat();    

foreach ($resultmenux as $row) {
    print_r($row);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM