Mysqli函数错误

时间:2017-06-20 09:04:14

标签: php mysqli

我一直在尝试更新一个函数来使用mysqli而不是mysql。该功能用于生成唯一的下载密钥。我一直收到错误:致命错误:在第20行的非对象上调用成员函数query()。 我无法弄清楚我的错误,希望有人能告诉我。感谢。

<?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))."')");


?>

3 个答案:

答案 0 :(得分:1)

将$ db变量作为参数传递给createKey函数,或者用作全局变量。我个人更喜欢把它作为参数传递 问题是您的实例中不存在db变量。因此,您应该将其作为参数传递

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

答案 1 :(得分:1)

您需要传递$db作为参数,因为它在函数范围内不可用

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);

答案 2 :(得分:0)

问题在于PHP变量范围。在引用$ db变量之前,在createKey()函数中添加 global $ 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