2012-02-01 103 views
0

我紛紛轉載此功能:我的功能有什麼問題?

function getTables() 
    { 
     global $db; 

     $value = array(); 
     if (!($result = $db->query('SHOW TABLES'))) { 
      return false; 
     } 
     while ($row = $db->fetchrow($result)) { 
      if (empty($this->tables) or in_array($row[0], $this->tables)) { 
       $value[] = $row[0]; 
      } 
     } 
     if (!sizeof($value)) { 
      $db->error("No tables found in database"); 
      return false; 
     } 
     return $value; 
    } 

以這種方式:

public function getTables() { 

    $value = array(); 

    $tables = array(); 

    $sql = "SHOW TABLES"; 

    if($stmt = $this->connect->prepare($sql)) { 
     $stmt->execute(); 
     while($row = $stmt->fetch_row()) {   
      if(empty($tables) or in_array($row[0], $tables)) { 
       $value[0] = $row[0]; 
      }  
     } 

     $stmt->close(); 

     if(!sizeof($value)) { 
      echo 'The database has no tables'; 
     } 

     return $value; 

    } else { 

     echo 'Couldn\t query the database'; 

    } 

} 

但第二個方法返回我The database has no tables因爲我在db一個表這是不正確的。

第二種方法有什麼問題?

如果你想知道什麼connect做:

public $connect; 
public function __construct() { 
    // Define The Database Connection Or Die If Failed Connecting 
    $this->connect = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(DB_CONNECTION_ERROR_MESSAGE); 
} 

使其與數據庫的連接。和prepare()這是一個mysqli聲明。我也試過query(),結果一樣。

+2

做一些調試。你的查詢返回了什麼?結果集中是否有行? – 2012-02-01 08:58:39

+0

'connect()'和'prepare()'做了什麼? – Corubba 2012-02-01 09:00:32

+0

讓我檢查查詢返回的內容。但結果只是'數組'。 – Roland 2012-02-01 09:01:01

回答

1

正確的代碼。使用query代替prepare

public function getTables() 
{ 
    $value = array(); 
    $tables = array(); 

    $sql = "SHOW TABLES"; 

    if ($res = $this->connect->query($sql)) 
    { 
     while ($row = $res->fetch_row()) 
     { 
      if (empty($tables) or in_array($row[0], $tables)) 
      { 
       $value[] = $row[0]; 
      } 
     } 

     if (!sizeof($value)) 
     { 
      echo 'The database has no tables'; 
     } 

     return $value; 
    } 
    else 
    { 
     echo 'Could not query the database'; 
    } 
} 

如果你仍然想使用prepare,那麼你還需要$stmt->bind_result$stmt->fetch()而不是fetch_row

+0

是的,但是我綁定的結果是什麼? – Roland 2012-02-01 09:26:01

+0

這就是我要說的。使用'query',不用擔心。對於這樣的查詢,「查詢」是理想的並且更加方便。 – dfsq 2012-02-01 09:29:24

+0

它現在可以工作,我得到'Array([0] => users)'。這就是我所需要的,因爲現在我將遍歷每個表並獲取所有行名稱和值,並將其輸出到一個sql文件中,就像您從phpMyAddmin中導出數據庫表一樣。 – Roland 2012-02-01 09:48:59

0

我覺得這段代碼被打破 $value[] = $row[0]; ,也許你應該將其更改爲 $value[0] = $row[0];array_push($value, $row[0])