This question already has an answer here:
I have problem with functions. I write them in config/funkcije.php. In folder config/ I have db.php which connects to database, etc... When I open in browser config/funkcije.php nothing shows on that page but it should echo out some results from DB.
This is my function:
include 'db.php';
function prikaz_posebne_ponude()
{
$sql = "SELECT * FROM posebna_ponuda ORDER BY id DESC LIMIT 1";
$sql1 = $mysqli->query("$sql");
while ($row = $sql1->fetch_assoc()) {
$glavni_naziv = $row[$lang];
if (empty($glavni_naziv)) {
echo '';
} else {
echo "<div class='row-banner'>";
echo "<h3><span>" . $langArray['rezervacija_smjestaja'] . "</span></h3>";
echo "<p>" . $glavni_naziv . "</p>";
echo "</div>";
}
}
}
But when I remove function prikaz_posebne_ponude(){ and } on the last line everything works fine. Why is this happening?
</div>
You define a function, but you never call it. Functions are reusable pieces of code, but to execute the contained statements, you have to call the function like this:
prikaz_posebne_ponude();
You also need to tell PHP that some variables are global (inside your function):
global $mysqli;
global $langArray;
global $lang;
Add at the end of this prikaz_posebne_ponude(); and you'll see the result. A function is made as a piece of code to be called everytime you need it.
First, variables you use in functions that are defined outside the function need to be global:
function prikaz_posebne_ponude()
{
global $mysqli;
global $langArray;
....
}
Then, you need to call the function for it to run:
prikaz_posebne_ponude();
You can either parse the necessary variables into the function:
function function_name ($con,$LangArray,$Lang){
/*
Manipulate here
*/
}
or make them global:
function function_name(){
global $mysqli;
global $langArray;
global $Lang;
}
then call:
$LangArray = array("test","test_1");
$Lang = "Value";
$mysqli = new mysqli("127.0.0.1","user","pass","db");
function_name($mysqli,$LangArray,$Lang);