2017-06-20 76 views
0

我一直在嘗試更新一個函數來使用mysqli而不是mysql。該功能用於生成唯一的下載密鑰。我不斷收到錯誤:致命錯誤:調用第20行非對象上的成員函數query()。 我無法弄清楚我錯了什麼,並希望有人可以給我看。謝謝。功能上的Mysqli錯誤

<?php 

$dbHost = 'localhost'; 
$dbUsername = 'xxx'; 
$dbPassword = 'xxx'; 
$dbName = 'xxx'; 


//Connect with the database 
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 


//error reporting 
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL); 



function createKey(){ 
    //create a random key 
    $strKey = md5(microtime()); 

    //check to make sure this key isnt already in use 
    $resCheck = "SELECT count(*) FROM downloads WHERE downloadkey = '{$strKey}' LIMIT 1"; 
    $arrCheck = $db->query($resCheck); 
    if($arrCheck['count(*)']){ 
     //key already in use 
     return createKey(); 
    }else{ 
     //key is OK 
     return $strKey; 
    } 
} 

//get a unique download key 
$strKey = createKey(); 

//insert the download record into the database 

$insert = $db->query("INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', 'onetimedownload.zip', '".(time()+(60*60*24*7))."')"); 


?> 
+2

變化'$ strKey = createKey();'到' $ strKey = createKey($ db);'並在你的函數中接收'$ db'。或者把'$ db'設爲全局。 –

回答

0

問題是與PHP變量範圍。添加全球$ DB內createKey()函數,你指的是$ DB變量之前:

function createKey(){ 

     global $db; // Add this line 

     //create a random key 
     $strKey = md5(microtime()); 

     //check to make sure this key isnt already in use 
     $resCheck = "SELECT count(*) FROM downloads WHERE downloadkey = '{$strKey}' LIMIT 1"; 
     $arrCheck = $db->query($resCheck); 
     if($arrCheck['count(*)']){ 
      //key already in use 
      return createKey(); 
     }else{ 
      //key is OK 
      return $strKey; 
     } 
    } 

瞭解更多關於變量的作用域在這裏:http://php.net/manual/en/language.variables.scope.php

+1

使用全局是非常非常不好的做法 – Akintunde007

1

將$ db變量作爲參數傳遞給函數createKey或用作全局變量。我個人更喜歡將它作爲參數傳遞。
問題是您的實例中不存在db變量。因此,爲什麼你應該把它作爲一個參數

function createKey($db) { // code goes here.. } 
1

你需要傳遞$db作爲參數,因爲它是不是在功能範圍awailable

function createKey($db){ 
    //create a random key 
    $strKey = md5(microtime()); 

    //check to make sure this key isnt already in use 
    $resCheck = "SELECT count(*) FROM downloads WHERE downloadkey = '{$strKey}' LIMIT 1"; 
    $arrCheck = $db->query($resCheck); 
    if($arrCheck['count(*)']){ 
     //key already in use 
     return createKey(); 
    }else{ 
     //key is OK 
     return $strKey; 
    } 
} 

//get a unique download key 
$strKey = createKey($db);