Sunday, 3 July 2016

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


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...