2016-08-20 66 views
-4

我coudnt在我的類上使用我的PDO mysql連接..你能幫我修改我的代碼嗎? (首先,它連接到數據庫,並檢查會話在__construct函數檢測成員的名字,然後寫最後的新聞..)OOP,PDO和MYSQL使用

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]; 
} 
} 
+0

什麼錯誤的PHP顯示? –

+0

空白頁:S @Gerald Chablowski – orhuncan

+0

您可以不使用注入而不是在您的contrsucter上調用pdo。此外,你應該使用新的\ Pdo(),就像它指的是JavaScript的名字空間。 –

回答

0

試試這個: 你失蹤的$ _SESSION [USER_ID]和報價參數在 - > fetch($參數); 使用PDO時,您前人的精力用一個嘗試捕捉,所以如果你有一個錯誤,你就會知道爲什麼連接使用PDO的

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]; 
} 
} 

例和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(); 
     } 
    } 
} 

每當你需要連接你會時間必須要求('connetion.php'); 並在其他類中使用它:

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 />"; 
     } 
    } 
}