2012-02-01 144 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])