在PHP中使用类并显示结果

时间:2014-08-18 13:01:06

标签: php mysql oop

我想显示我从php中的mysql数据库中检索的结果。

我有一个文件调用db_functions.php,其中包含以下内容:

<?php

class DB_Functions {

        private $con;

        // constructor
        function __construct() {
            require_once __DIR__.'/db_connect.php';
            // connecting to database
            $db = new DB_Connect();
            $this->con = $db->getDbConnection();
        }

        public function selectUser($id) {

            try {
                $stmt = $this->con->prepare('SELECT * FROM user WHERE id = :id');

                $params = array(':id' => $id);

                $stmt->execute($params);

                return $stmt;

            } catch(PDOException $e) {

                echo 'ERROR: ' . $e->getMessage();

            }

        }

        public function otherSQLfunction($parameter) {
                 // other sql code
        }
}

然后我用:

调用该函数
<?php

     require_once __DIR__.'/db_functions.php';

     $db = new DB_Functions();

     $result = $db->selectUser($id);



?>

如何使用此功能并显示结果,让我说我只想让它显示&#34; affID&#34;

1 个答案:

答案 0 :(得分:0)

您呼叫selectUser功能,它将返回$stmtecho 'ERROR: ' . $e->getMessage();

如果它返回$stmt,该变量将存储在您的$result变量中。

然后,您可以使用$result,但是您可以这样做(echo $resultforeach $result as $item等)。