Search code examples
phpmysqliprepared-statementnested-function

mysqli prepared statement - nested function does not perform


Nested function inside of fetch (which is inside of another function) does not perform.

fn_smth1 is nested inside of fn_smth2 and should output result via fn_smth2

Example below is a simplified version.

function fn_smth1 ($id){
    global $mysqli;
    $stmt = $mysqli->stmt_init();
    if ($stmt->prepare("SELECT code FROM at WHERE id = ?")){
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $stmt->bind_result($code);
        if ($stmt->fetch()){
            $code_displ = $code; 
        }
    }
    $stmt->close;
    return $code_displ;
}


function fn_smth2($id){
    global $mysqli;
    $stmt = $mysqli->stmt_init();
    if ($stmt->prepare("SELECT idx, name FROM at WHERE id = ?")){
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $stmt->bind_result($idx, $name);
        if ($stmt->fetch()){
            $code_displ = $name.' === '.fn_smth1($idx); 
        }
    }
    $stmt->close;
    return $code_displ;
}


echo fn_smth2(1);

//expected

some name here === some code here

//received

some name here === null (function fn_smth1 does not give a value)


Solution

  • You're trying to execute second prepared statement, while the resultset from the first one has not been stored yet. Use mysqli_stmt::store_result() before trying to execute second statement.