Jump to content

PHP PDO Sql connection from a Class.

G1K777

Hi,

I'm trying to connect to my database and it doesn't work for some reason.

Why isn't this working? Woke up at 2am and now sitting and doing the login system.

userlist.php
 

include_once 'dbh.php';

class Users extends Dbh
{
    private $sql = 'SELECT id,username FROM users';

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

    public function getUsers(){
        return $this->conn->query($this->sql);
    }
}

$users = new Users();

$result = $users->getUsers();
echo var_dump($result);

dbh.php
 

<?php

class Dbh
{
    private $host = '127.0.0.1';
    private $port = '3306';
    private $username = 'root';
    private $password = '123';
    private $dbname = 'loginsystemdb';
    private $charset = 'utf8mb4';

    protected $conn;

    function __construct()
    {
        try {
            $this->conn = new PDO("mysql:host=$this->host;port=$this->port;dbname=$this->dbname;charset=$this->charset", $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (PDOException $e) {
            echo 'Mysql Connection failed: '.$e->getMessage();
        }
    }
}

 

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

You should use the prepare method

<?php

$statement = $this->conn->prepare($this->sql);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_ASSOC);

 

Business Management Student @ University St. Gallen (Switzerland)

HomeServer: i7 4930k - GTX 1070ti - ASUS Rampage IV Gene - 32Gb Ram

Laptop: MacBook Pro Retina 15" 2018

Operating Systems (Virtualised using VMware): Windows Pro 10, Cent OS 7

Occupation: Software Engineer

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×