2014-10-31 66 views
0

我一直在試圖使用一個函數而沒有聲明它的第二個參數,但它似乎不工作。我做錯了什麼?嘗試使用沒有第二個參數的函數

我也嘗試聲明函數沒有第二個參數$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(); 
    } 

} 
?> 

回答

3

在數據庫級更改

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

呼叫無第2個參數

$db->DoQuery($query); 

呼叫與第二個參數

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

'$ DB-> DoQuery($查詢,NULL);'不起作用[** **見(http://php.net/manual/en/functions.arguments.php# functions.arguments.default) – 2014-10-31 17:21:00

+0

你能否詳細說明一下? – 2014-10-31 17:25:51

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); 
相關問題