【问题标题】:What is wrong with my function?我的功能有什么问题?
【发布时间】:2012-02-01 08:57:09
【问题描述】:

我已经复制了这个功能:

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,这是不正确的,因为我在数据库中有一个表。

第二种方法有什么问题?

如果你想知道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(),结果一样。

【问题讨论】:

  • 做一些调试。您的查询返回什么?结果集中有行吗?
  • connect()prepare() 在做什么?
  • 让我检查一下查询返回的内容。但结果只是Array
  • 我在您的编辑中看到现在包括连接。尝试check for errors。我删除了我以前的答案。

标签: php mysql


【解决方案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

【讨论】:

  • 是的,但是我绑定的结果是什么?
  • 这就是我在说的。使用query,不用担心。对于此类查询,query 是理想且更方便的。
  • 它现在可以工作了,我得到了Array ( [0] => users )。这就是我所需要的,因为现在我将遍历每个表并获取所有行名和值并将其输出到 sql 文件中,就像从 phpMyAddmin 导出数据库表一样。
【解决方案2】:

我认为这段代码坏了 $value[] = $row[0]; 也许你应该把它改成 $value[0] = $row[0];array_push($value, $row[0])

【讨论】:

    猜你喜欢
    • 2012-05-27
    • 1970-01-01
    • 2018-02-19
    • 2015-05-27
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多