duanmiaosi0150 2016-05-07 05:28
浏览 21

PDO数据库不向数据库添加项目

I have just got a school assignment to practice PDO. The problem is i seem to get it to connect to database but can't get it to insert or count rows in database. This might be a possible duplicate question did try to search for answers but might just been asking wrong questions.

<?php
 include("db.class.php");

 class uppClass extends Database {

    function __construct() {
        parent::__construct();
    }

    public function countUsers() {
        $stmt = $this->connection->prepare("SELECT * FROM users LIMIT 500");
        $stmt->execute();
        return count( $stmt->fetchAll(PDO::FETCH_ASSOC) );
    }

}
?>

next class handles the pdo connection

<?php
include("db-details.php");

class Database {

    public $connection;

    /**
     * Opens a connection to the DB
     */

    public function __construct() {
        try {
            $this->connection = new PDO("mysql:host=$this->DATABASE_ADDRESS;dbname=$this->DATABASE_NAME;", DATABASE_USERNAME, DATABASE_PASSWORD);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
            $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
    } 

}
?>
  • 写回答

1条回答 默认 最新

  • douxiegan6468 2016-05-07 08:50
    关注

    To count the rows using PDO you can use this.

    public function countUsers() {
        $stmt = $this->connection->prepare("SELECT * FROM users LIMIT 500");
        $stmt->execute();
        $stmt->fetchAll(PDO::FETCH_ASSOC); 
        return $stmt->rowCount();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘