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 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题