learning php for some time, maybe I miss some fundamental concept about this-> and selft::, but here is my example:
Firts, I have this :
class DB {
private static function getDBConnection() {
$dbconfig = parse_ini_file(ROOT_DIR."\include\config.ini");
$serverName = $dbconfig["sqlserver"];
$connectionInfo = ["Database"=>$dbconfig["database"],"UID"=>$dbconfig["dbuser"],"PWD"=>$dbconfig["password"]];
$conn = sqlsrv_connect($serverName,$connectionInfo);
if ($conn === false) {
echo "Could not connect.\n";
die(print_r(sqlsrv_errors(), true));
}
return $conn;
}
Then I have this, but when executing the sqlsrv_fetch_array later throws an error:
public static function queryDB($query, $params = array()) {
try{
if ($stmt = sqlsrv_query(self::getDBConnection(), $query, $params)) {
echo "Statement completed.\n";
} else {
echo "Statement could not be completed.\n";
die(print_r(sqlsrv_errors(), true));
}
$data=sqlsrv_fetch_array($stmt);
return $data;
}
catch(Exception $ex){
echo "Statement could not be executed.\n $ex->getMesssage()";
die(print_r(sqlsrv_errors(), true));
}
finally{
/* Free the statement and connection resources. */
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
}
However, this works fine adding $conn = self::getDBConnection(); :
public static function queryDB($query, $params = array()) {
$conn = self::getDBConnection();
try{
if ($stmt = sqlsrv_query($conn, $query, $params)) {
echo "Statement completed.\n";
} else {
echo "Statement could not be completed.\n";
die(print_r(sqlsrv_errors(), true));
}
$data=sqlsrv_fetch_array($stmt);
return $data;
}
catch(Exception $ex){
echo "Statement could not be executed.\n $ex->getMesssage()";
die(print_r(sqlsrv_errors(), true));
}
finally{
/* Free the statement and connection resources. */
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
}
My question is why I have to set it to a local variable and not just use it inside the sqlsrv_fetch_array call ? It may be simple but I want to learn WHY . Thanks !!