When writing prepared statement and binding the results using a bind_result()
statement (referenced here), considering the example below, do I need to declare $a
, $b
or $c
before it's bound in the statement?
$a = ""; //does this declaration need to happen?
$stmtGetData = $conn1->prepare("SELECT a, b, c FROM myTable");
$stmtGetData->execute();
$stmtGetData->bind_result($a, $b, $c);
$stmtGetData->fetch();
$stmtGetData->close();
The code seems to work either way whether or not the variables are declared before the bind_result()
. While the PHP documentation referenced above does not show the variables being declared, Intelephense shows an Undefined variable
exception if they are not.
My impression is that Intelephense is just not picking up on the fact that this is 'okay', but I want to make sure that I am doing this the correct way.
It might not be easy to understand, but when you pass variables by reference to bind_result()
you are actually defining them. You don't need to declare them before.
You can easily test this assumption:
function test(mysqli $conn1){
$a = ""; //does this declaration need to happen?
$stmtGetData = $conn1->prepare("SELECT 1,2,3");
$stmtGetData->execute();
$stmtGetData->bind_result($a, $b, $c);
var_dump($a, $b, $c);
}
test($mysqli);
// Outputs the following with no warnings about undefined variables
// string(0) ""
// NULL
// NULL
If the variables $b
and $c
were undefined, you would get a warning when trying to use it var_dump
.
There could be a couple of reasons why Intelephense tells you these variables are undefined:
mysqli
correctly as the parameter type. Check the namespace or always use a fully qualified name.mysqli
object variable name. Is it really $conn1
in your current scope?