PHP简单的功能不起作用

时间:2013-07-10 23:45:38

标签: php sql function

我无法做出简单的回音。

我有一个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; ?>

所以我的问题是,代码无效。我无法回应我的数据。你能帮帮我吗?

1 个答案:

答案 0 :(得分: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函数非静态,并使成员字段指向您的数据库。