-4

I coudnt use my PDO mysql connection on my classes.. Could you help me to modify my code? (first of all, its connecting to database and checking session to detect member name in __construct function, then write last news..)

class Content {

public function __construct() {

public $db = new PDO("mysql:host=localhost;dbname=XXXX;
charset=utf8", "XXXX", "XXXX");

$db->exec('SET NAMES `UTF-8`');

if ($_SESSION[user_id])  {  
$query = $db->query("SELECT count(id),name FROM members 
WHERE id = '$_SESSION[user_id] LIMIT 1")->fetch(); }

 }

public function WriteContent() {
$news = $db->query("SELECT * FROM news ORDER BY id DESC LIMIT 1")->fetch();
echo 'hi'.$query[name].'<br/><br/>'.$news[headline].'<br/>'.$news[detail];
}
}
orhuncan
  • 11
  • 4

1 Answers1

0

Try this: You were missing the quotes of $_SESSION[user_id] and the argument in ->fetch($argument); You sould use a try catch when using pdo so if you have a mistake you will know why

class Content {

public function __construct() {

public $db = new PDO("mysql:host=localhost;dbname=XXXX;
charset=utf8", "XXXX", "XXXX");

$db->exec('SET NAMES `UTF-8`');

if (isset($_SESSION['user_id'])){  
    $userId=$_SESSION['user_id'];
    $query = $db->query("SELECT count(id),name FROM members 
    WHERE id = $userId LIMIT 1")->fetch(PDO::FETCH_ASSOC); 
    }   
}

public function WriteContent() {
$news = $db->query("SELECT * FROM news ORDER BY id DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
echo 'hi'.$query[name].'<br/><br/>'.$news[headline].'<br/>'.$news[detail];
}
}

Example of a connection using PDO and OOP

class Connection{
    protected $con; //connection variable

    public function Conexion(){
        try{
            $this->con=new PDO("mysql:host=localhost;dbname=Youtube","root","");
            $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);     
            $this->con->exec("SET CHARACTER SET UTF8");
            return $this->con;
        }
        catch (PDOException $e){
            echo "Error: " . $e->getMessage() . "<br />Line: " .   $e->getLine();
        }
    }
}

Every time you need the connection you will have to do require('connetion.php'); and to use it in other class:

Class ViewDataBaseResults extends Connection{
    public function ViewDataBaseResults(){
        parent::__construct(); //You inherit the construct here
    }
    public function view(){
        $result=$this->con->query("SELECT * FROM TABLE"); //
        if($array=$result->fetch(PDO::FETCH_ASSOC));{
             echo "Hi: " . $array['name'] . "<br />";
        }
    }
}
Heriberto Juarez
  • 270
  • 2
  • 18