哪个对象丢失了?

时间:2015-03-13 11:19:49

标签: php mysqli

我无法理解为什么会出现此错误。我知道这些错误出现的明显原因,但我确实看了看并重新审视了我的代码而无法理解为什么!

错误是:

  

致命错误:在非对象上调用成员函数prepare()

以下是代码段。

db_connect.php

<?php
include_once 'psl-config.php';   // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);

customer.php

include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
.
.
.
function myCallBackFunction($array) {
                //echo ".";
               // print_r($array);

                $amount=$array['amount'];
                $date=$array['date'];                    
                if(transaction($mysqli, $date, $amount))
                {
                    echo "Transaction table Updated";
                }
            }

的functions.php

//Function to insert transactions
function transaction($mysqli, $date, $amount) {
    if($smt = $mysqli->prepare("INSERT INTO `tbltransaction` (entry_date,income) VALUES (?,?)
  ON DUPLICATE KEY UPDATE income=income+?;"));
    {
        $stmt->bind_param('sii', $date, $amount, $amount);  // Bind "$date" and "$amount" to parameter.               
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();
        if ($stmt->num_rows == 1) {
            return true;
        } else {
            return false;
        }
    }

}

tbltransaction

Column  Type    Null    Default     Comments    MIME
entry_date  date    No           
income  int(11) No 

P.S:functions.php文件中的另一个函数运行正常,这是函数和我调用它的方式

功能

//Function to display notice
function notice($mysqli) {
    $notice = null;
    if ($stmt = $mysqli->prepare("SELECT notice FROM tblnotice ORDER BY ID DESC LIMIT 1")) {
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();
        // get variables from result.
        $stmt->bind_result($notice);
        $stmt->fetch();
        return $notice;
    }
}

调用函数

<?php echo notice($mysqli); ?>

2 个答案:

答案 0 :(得分:2)

这是一个可变范围问题 - 您需要将$mysqli对象作为第二个参数传递给myCallBackFunction函数,否则它将不会在该函数内设置。

像这样:

function myCallBackFunction($array, $mysqli) {

然后,在您调用该函数的地方,您需要传入$mysqli对象:

myCallBackFunction($array, $mysqli);

答案 1 :(得分:0)

你可以选择

function notice() {
  global $mysqli;
    $notice = null;
    if ($stmt = $mysqli->prepare("SELECT notice FROM tblnotice ORDER BY ID DESC LIMIT 1")) {
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();
        // get variables from result.
        $stmt->bind_result($notice);
        $stmt->fetch();
        return $notice;
    }
}