2017-06-14 90 views
-1

我想获取表上的数据并写一个类。但是这个类不工作,因为pdo不能访问。我怎样才能得到这个类的表数据?PHP PDO类在不同的类中使用(不起作用)

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


class uye extends PDO{ 
    var $id; 
    var $kadi; 

    function cek($id){ 
     $query = $db->query("SELECT * FROM btc WHERE id='{$id}'", PDO::FETCH_ASSOC); 
     if ($query->rowCount()) { 
      foreach($query as $row){ 
       $this->id=$row["id"]; 
       $this->kadi=$row["kadi"]; 
      } 
     } 
    } 
} 


$bilgiler=new uye; 
$bilgiler->cek(1); 

echo $bilgiler->kadi; 
+0

您可以发布您从 – Option

+0

调用此类的另一个文件吗您在您的语句中也容易受到SQL注入的影响 – Option

+1

您准备做什么?您的类扩展了PDO,但尝试使用另一个PDO实例。你想做什么? –

回答

0

所以我不知道在哪里您取得$id我跑这一关获取的所有数据。

我通常会将我的代码分解为文件和文件夹,因为我发现这更容易与其他人合作。

// database connection file (dbc.php) 



class Database 
{ 
    private $host = "127.0.0.1"; 
    private $db = ""; 
    private $user = ""; 
    private $password = ""; 
    public $conn; 



    public function dbConnect() 
    { 
     $this->conn = null; 
     try 
     { 
      $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db, $this->user, $this->password); 
      $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     } 
     catch (PDOException $exception) 
     { 
      echo "Connection error: " . $exception->getMessage(); 
     } 

     return $this->conn; 

    } 
} 

我然后做一个普通的文件,在这里,您可以存储所有常用的功能或你的静态功能

// Common file (common.php) 


require_once('dbc.php'); 

class DBCommon 
{ 
    private $conn; 

    public function __construct() 
    { 
     $database = new Database(); 
     $db = $database->dbConnect(); 
     $this->conn = $db; 
    } 

    public function run($sql) 
    { 
     $stmt = $this->conn->prepare($sql); 
     return $stmt; 
    } 


} 

所以要更多地解释这一点,你会看到一个功能的run()这仅仅是节省了繁琐的$this->conn->prepare每个查询。现在你可以运行$this->run()

下一个会是你的类文件..这是你的逻辑是:

// your class file... (class.btc.php) 


require_once "common.php"; 


class BTC extends DBCommon 

{ 
    public function getQuery() 
    { 
     $stmt = $this->run("SELECT * FROM `btc`"); 
     $stmt->execute(); 

     while ($row = $stmt->fetch(PDO::FETCH_OBJ)) 
     { 
      $rows[] = $row; 
     } 

     return $rows; 

    } 

} 

自我解释..

然后你调用方法..比方说index.php

// File you're calling your class from (index.php) 


    require_once "class.btc.php"; 

    $fetch = new BTC(); 

    $returnData = $fetch->getQuery(); 


    foreach ($returnData as $data) 
    { 
     echo 
     "<p>$data->something</p> 
     <p>$data->somethingElse</p>"; 
    } 

这似乎有点长篇大论,我知道,但时间你会整体保存会帮助!

+0

感谢您的帮助。但这种方法很长。你知道最短的方法吗? – Yunus

+0

相关:[报告PDO错误](https://phpdelusions.net/pdo#reporting_errors)和[捕捉PDO例外](https://phpdelusions.net/pdo#catch) –

+0

@Yunus,这是一个漫长的过程开始是的,但是,一个最初的文件被设置,它要快得多。 – Option