Hi,

function openingBalance($accountNum) {
	$sql_OpenBal = " SELECT closing_balance FROM bank_balance				WHERE bank_account.account_no = $accountNum ";
	$runSql = mysqli_query($mysqli, $sql_OpenBal);...

Red line generates an error. "Warning: mysqli_query() expects parameter 1 to be mysqli, null given".

I call function echo openingBalance (1500); How can i search $accountNum in SQL statement?
Thanks

Dani AI

Generated

As discovered, the real cause was scope: the mysqli handle you used inside the function wasn’t available there, so the query call got a null connection. Placing the connection code inside the function fixes it, but it’s not the best pattern for maintainability or performance. Prefer passing the existing connection into the function (or use dependency injection) and use prepared statements to avoid SQL injection.

A concise, safe pattern:

function openingBalance($mysqli, $accountNum) {
    $stmt = $mysqli->prepare("SELECT closing_balance FROM bank_balance WHERE account_no = ?");
    if ($stmt === false) {
        throw new Exception($mysqli->error);
    }
    $stmt->bind_param("i", $accountNum);
    $stmt->execute();
    $stmt->bind_result($closing);
    $stmt->fetch();
    $stmt->close();
    return $closing;
}

Call it with your established connection rather than reconnecting every time. If you must open a connection inside the function, make sure to reuse persistent connections or otherwise avoid doing that on every request.

Quick troubleshooting checklist:

  • Verify the table/column reference. Your original WHERE referenced bank_account.account_no while selecting from bank_balance — use proper joins or the correct table.column.
  • Check the connection object before queries and handle prepare/execute failures.
  • If the value is strictly numeric, intval() can help, but prepared statements are safer.
  • For robust debugging enable mysqli exceptions or use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT).

See PHP variable scope and mysqli prepared statement docs for details: PHP variable scope and mysqli::prepare.

solved. I added database conenction string into function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.