2016-01-21 80 views
0

我创建了一个函数来从我的数据库中获取数据。我希望这个函数可以重复使用,只需要为不同的表放置正确的参数即可。下面是我做了什么:在函数pdo中传递参数php

public function selectdata($table, $arguments='*', $where = null){ 
    if($this->isconnect){ 

     //check whether users put column names in the select clause 

     if(is_array($arguments)){ 

      $new_args = implode(',', $arguments); 
      $sql  = 'SELECT '.$new_args.' FROM '.$table; 

     } else { 

      $sql  = 'SELECT '.$arguments.' FROM '.$table; 

     } 

     //check whether users use the where clause 

     if($where != null && is_array($where)){ 

      $where = implode(' ', $where); 
      $sql .= ' WHERE '.$where ; 

     } 

     $query = $this->db->query($sql); 
     $query -> SetFetchMode(PDO::FETCH_NUM); 
     while($row = $query->fetch()){ 
      print_r($row); 
     } 


    } else { 
     echo 'failed, moron'; 
    } 
} 

这是运行函数的方式:

$columnname = array('bookname'); 
$where  = array('bookid','=','2'); 
echo $database-> selectdata('buku', $columnname, $where); 

的代码做得很体面,到目前为止,但我不知道我要怎么使用$where但在功能中没有$columnname。我如何传递函数中的参数?

你能指点我更好的方法来创建一个函数来使用PDO抓取数据吗?

回答

0

只需使用一个PDO类可以是这样的:

<?php 
class DB_Connect{ 
    var $dbh; 
    function __construct(){ 
     $host = "xxx"; 
     $db = "xxx"; 
     $user = "xxx"; 
     $password = "xxx"; 
     $this -> dbh = $this -> db_connect($host, $db, $user, $password); 
    } 
    public function getDBConnection(){ 
     return $this -> dbh; 
    } 
    protected function db_connect($host, $db, $user, $password){ 
     //var_dump($host, $db, $user, $password);exit(); 
     try { 
      $dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password); 
     } 
     catch(PDOException $err) { 
      echo "Error: ".$err->getMessage()."<br/>"; 
      die(); 
     } 
     return $dbh; 
    } 
    public function query($statement){ 
     $keyword = substr(strtoupper($statement), 0, strpos($statement, " ")); 
     $dbh = $this->getDBConnection();   
     if($dbh){ 
      try{ 
       $sql = $dbh->prepare($statement); 
       $exe = $sql->execute(); 
      } 
      catch(PDOException $err){ 
       return $err->getMessage(); 
      } 
      switch($keyword){ 
       case "SELECT":     
        $result = array(); 
        while($row = $sql->fetch(PDO::FETCH_ASSOC)){       
         $result[] = $row;      
        } 
        return $result;     
        break; 
       default: 
        return $exe; 
        break; 
      } 
     } 
     else{ 
      return false; 
     } 
    } 
} 
?> 

现在你可以包括类以及$dbh = new DB_Connect;创建一个对象,然后调用你只想与$dbh->query($statement) 参考每条语句这是我的最好的方式来做到这一点。

编辑:如果您想使用的语句在另一个数据库,只需使用__construct($db)方法来传递对象创建

+0

有什么'$ keyword'变量的函数你的数据库的名字吗? – januaryananda

+0

如果需要获取结果,'$ keyword'变量将被分开!如果你从你的数据库中选择了一些东西,那么你可以得到格式良好的数组,例如'$ array [“counter”] [“Field_Key”]''。 (“计数器”是你用'0'开始的结果数量) –

+0

@januaryananda是你想要的答案吗? –