-2

我无法做出简单的回声。

我有一个 admin.class.php

public static function get_quota() {
  return self::find_by_sql("SELECT * FROM quota");
}

public static function find_by_sql($sql="") { 
  global $database; 
  $result_set = $database->query($sql); 
  $object_array = array(); 
  while ($row = $database->fetch_array($result_set)) { 
    $object_array[] = self::instantiate($row); 
  } 
  return $object_array; 
}

还有我在 index.php 中的回显代码

<?php
    $admin = User::find_by_id($_SESSION['user_id']);
    $admin_class = new Admin();
    $get_quota = Admin::get_quota();
    $sql = "SELECT * FROM quota";
    $get_quota = Admin::find_by_sql($sql);
?>
.
.
.
<?php echo $get_quota->daily_a; ?>

所以我的问题是,代码不起作用。我无法回显我的数据。你能帮我吗?

4

1 回答 1

0

你在这里有几个问题:

<?php echo $get_quota->daily_a; ?>

此行引用$get_quota变量并搜索成员字段daily_a。尝试这个:

<?php echo "Quota is:".var_export($get_quota->daily_a,true); ?>

这将表明这只是一个空变量。

但是,还要注意:

$get_quota = Admin::get_quota();
$sql = "SELECT * FROM quota";
$get_quota = Admin::find_by_sql($sql);

在这里,您将调用两个单独的方法Admin并将变量设置$get_quota为结果。第二个覆盖第一个。因此,该get_quota()方法在这里对我们没有帮助:我们需要知道您的find_by_sql()方法返回什么。

编辑(发布新代码添加到问题)

您可以在遇到问题的函数中实现日志记录/回显:

public static function find_by_sql($sql="") { 
  global $database; //Note this is bad practice (1).
  $result_set = $database->query($sql); 
  echo "Result Set: ".var_export($result_set,true)."\n";//This should return something if you're getting something back from the database. Also, remove this for runtime (obviously).

  if (count($result_set) <= 0) { //constraint checking is always good! And cheap!
    error_log("An unexpected number of rows (0) was received from the database for query='".$sql."'.");
  }

  $object_array = array(); 
  while ($row = $database->fetch_array($result_set)) { 
    $object_array[] = self::instantiate($row); //Ensure that the instantiate function returns something!
  } 

  echo "Object Array: ".var_export($object_array, true)."\n";//double-check your instantiate function is working
  return $object_array; 
}

根据此代码,您的问题可能与实例化函数有关;如果它没有返回任何东西,$object_array可能是空的。(但不是空的!)。

(1) 你应该避免像这样抓取全局变量。相反,实例化一个持有和管理数据库连接的类。然后使您的find_by_sql函数非静态,并有一个指向您的数据库的成员字段。

于 2013-07-10T23:49:55.977 回答