douchensou6495 2017-04-10 08:32
浏览 35
已采纳

使用PDO的类和方法,以及检索数据

I'm new to OOP programming, and I'm really lost with this what the title says. When I try to put the query in a class and in another file, I get errors in a file called Main.php and don't even know what to do to fix them:

Notice: Undefined variable: sth in Select.php on line 10

Fatal error: Cannot access empty property in Select.php on line 10

If I put the select in Connection.php, it returns the rows just fine, but with classes, I get those.

Here's my code:

Connection.php:

<?php
$hostname = 'localhost';
$username = 'user';
$password = 'pass';

function connectDB ($hostname, $username, $password){
    $dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
    return $dbh;
}

$dbh = connectDB ($hostname, $username, $password);
echo 'Connected to database <br/>';

Select.php:

<?php require_once 'Connection.php';
class Select {

    public function select() {
        $sql= "select * from table limit 10; <br/>";
        echo $sql;
        $select = $dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);

        foreach($this->$sth as $row){
            echo $row['column']."<br/>";
        }
    }
}

The question is, how can I print the result from the query (for example from main.php, which has an autoloader), and why do I get those errors, when on a single file, they work just fine?

Edit:

<?php
    $test = new Select($dbh);
    echo $test->select();
?>

Besides the fixes in the replies, I included Connection.php into the main.php, changed the echo in Select.php to return and it works perfectly now. Adding this in case someone ever gets as lost as me.

  • 写回答

1条回答 默认 最新

  • doumo2501 2017-04-10 08:43
    关注

    You do not want to iterate over the query, but the result of that query. So this probably is what you are looking for:

    <?php
    class Select {
        public function select() {
            $sql= 'select * from table limit 10';
            $select = $dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
    
            foreach($select as $row){
                echo $row['column']."<br/>";
            }
        }
    }
    

    And you also need to take care that the $dbh object is actually present inside that method. Either inject it into the object or specify it as method argument. So your full class will probably look something like that:

    <?php
    class Select {
        private $dbh;
        public function __construct($dbh) {
            $this->dbh = $dbh;
        }
        public function select() {
            $sql= 'select * from table limit 10';
            $select = $this->dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
    
            foreach($select as $row){
                echo $row['column']."<br/>";
            }
        }
    }
    

    And you instantiate the object like that:

    $selectObj = new Select($dbh);
    

    Some general warning, though: Using PDO's fetchall() method is convenient, but carries a huge risk: it means that the full result set has to be copied into an array inside the php script. For bigger results that may lead to issues with memory usage (scripts getting terminated for security reasons). Often it is the better approach to use a while loop over a single row fetched from the result set in each iteration.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来