Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


php pdo mysql how to use database connection across different classes using -'php,mysql,class,pdo'


php pdo mysql how to use database connection across different classes  using -'php,mysql,class,pdo'

I'm kinda new to PDO with MYSQL, here are my two files:

I have a connection class that I use to connect to the database:

class connection{

private $host = 'localhost';
private $dbname = 'devac';
private $username = 'root';
private $password ='';  

public $con = '';

function __construct(){

    $this->connect();   

}

function connect(){

    try{

        $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
        $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);


    }catch(PDOException $e){

        echo 'We\'re sorry but there was an error while trying to connect to the database';
        file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);

    }
}   
}


I have an account_info class that i use to query the data from the database:

class account_info{


function getAccountInfo(){

    $acc_info = $this->con->prepare("SELECT * FROM account_info");
    $acc_info->execute();

    $results = $acc_info->fetchAll(PDO::FETCH_OBJ);

    foreach ($results as $key) {
        $results->owner_firstname;

    }
}       


}


I include both these files in my index.php page:

include_once 'classes/connection.class.php';
include_once 'classes/accountinfo.class.php';

$con = new connection();
$info = new account_info();
$info->getAccountInfo();


I just cant get it to work I'm not getting any output, I think it has something to do with the scope, but I don't know the correct why to fix it as I'm new to this PDO and OOP stuff.
Thanks in advance.
    

asked Sep 7, 2015 by rajesh
0 votes
11 views



Related Hot Questions



Walkin Jobs Opening



Government Jobs Opening


...