The Only Smart Boy
The Only Smart Boy

Reputation: 575

Array to string conversion php mysqli execute

I am trying to retrieve data from database using this function

     public function checkBalance($account) {
    $stmt = $this->conn->prepare("SELECT balance FROM tbl_accounts WHERE ac_no = ?");
    $stmt->bind_param("s", $account);
    if ($stmt->execute()) {
        $balance = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $balance['balance'];
    } else {
        return NULL;
    }
}

the function is being called and value passed to it as follows

    $balance = $db->checkBalance($account);
    if ($balance != NULL) {
        $response["error"] = FALSE;
        $response["balance"]["amount"] = $balance;
        echo json_encode($response);
    } else {
    // Unable to get balance
        $response["error"] = TRUE;
        $response["error_msg"] = "Transaction failed!";
        echo json_encode($response);
    }

My problem is that this return null and the error

     Notice: Array to string conversion in C:\wamp\www\mlipaapi\db\DB_Functions.php on line 226
Call Stack
#   Time    Memory  Function    Location
1   0.0009  407848  {main}( )   ...\getbalance.php:0
2   0.0159  458952  DB_Functions->checkBalance( )   ...\getbalance.php:22
3   0.0160  484864  execute ( ) ...\DB_Functions.php:226
{"error":true,"error_msg":"Transaction failed!"}

What am I doing wrong? the line mentioned is if ($stmt->execute()) {

Upvotes: 0

Views: 393

Answers (1)

Dharman
Dharman

Reputation: 33238

mysqli_stmt::execute() expects all arguments to be scalar values. Your variable $account is an array, and PHP is not able to cast an array to a string.

If you want to bind a single element from the array then use the array access operator to select the correct element, either inside or outside of your function. Strict typing of your function parameters would definitely help you avoid the mistake.

public function checkBalance(string $account) {
    $stmt = $this->conn->prepare("SELECT balance FROM tbl_accounts WHERE ac_no = ?");
    $stmt->bind_param("s", $account);
    $stmt->execute();
    $balance = $stmt->get_result()->fetch_assoc();
    return $balance['balance'] ?? null;
}

// When calling pass a single element from the array.
$balance = $db->checkBalance($account[42]);

If your intention is to bind multiple values using an array of strings then the correct approach would be to create a string of letters denoting the type, and then unpack the array. Please note the parameter type of the function and the syntax used in bind_param().

public function checkBalance(array $account) {
    $stmt = $this->conn->prepare("SELECT balance FROM tbl_accounts WHERE ac_no = ?");
    $stmt->bind_param(str_repeat("s", count($account)), ...$account);
    $stmt->execute();
    $balance = $stmt->get_result()->fetch_assoc();
    return $balance['balance'] ?? null;
}

Upvotes: 1

Related Questions