尝试使用没有第二个参数的函数

时间:2014-10-31 15:06:22

标签: php function pdo parameters

我一直试图在不声明其第二个参数的情况下使用函数,但它似乎无法正常工作。我做错了什么?

我也尝试在没有第二个参数$db->DoQuery($query, null);的情况下声明函数,结果相同。

<?php 
include($directory . "classes/database.php");
$db = new database;
$db->initiate();
include("../includes/core.php");
$query = "SELECT * FROM services";
$db->DoQuery($query, null);
$num = $db->fetchAll();
print_r($num);
?>

以下是数据库类。

<?php
class database {
  public function initiate() {
    $user             = "user";
    $password         = "pass";
    $hostname         = "localhost";
    $dbn              = "dbt";

    try
    {
      $this->database = new PDO("mysql:host={$hostname};dbname={$dbn}", $user, $password);
    }
    catch(PDOException $e)
    { 
      $error = "I'm unable to connect to the database server.";
      die("Failed to connect to database: " . $e->getMessage());
    }

    $this->database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

  public function DoQuery($query, $query_params) {
    try
    {
      $this->result = $this->database->prepare($query);
      if ($query_params != null)
      {
        $this->result->execute($query_params);
      }
      else
      {
        $this->result->execute();
      }
    }
    catch(PDOException $e)
    {
      die();
    }
  }

  // A function to fetch a single row from the query
  public function fetch() {
    return $this->result->fetch();
  }

  // A function to fetch multiple rows from the query
  public function fetchAll() {
    return $this->result->fetchAll();
  }

    // A function to fetch number of rows from the query
  public function RowCount() {
    return $this->result->RowCount();
  }

}
?>

2 个答案:

答案 0 :(得分:3)

数据库类的更改

public function DoQuery($query, $query_params = null) {

没有第二个参数的呼叫

$db->DoQuery($query);

使用第二个参数调用

$db->DoQuery($query, null);

答案 1 :(得分:0)

将第二个参数设置为array()

public function DoQuery($query, $query_params = array()) {
    try
    {
      $this->result = $this->database->prepare($query);
      $this->result->execute($query_params);
    }
    catch(PDOException $e)
    {
      die();
    }
}

然后,如果您不想传递任何查询参数,则只需省略第二个参数。

$db->DoQuery($query);