0

I was just organizing one of my codes and notice that leaving the connect-mydb.php out of a function, it doesnt work. I always thought the include would be loaded prior to any of the functions.

connect-mydb.php

<?php
$server = 'localhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydb';
$mysqli = new mysqli($server, $user, $pass, $db);
?>

testdb_out.php (doesnt work)

<?php
include 'connect-mydb.php';

function UpdateDB() {
echo "working\n";
$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
  echo 'success';
}else{
  echo 'failed';
}
}
UpdateDB();
?>

testdb_within.php (works)

<?php
function UpdateDB() {
include 'connect-mydb.php';

$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
  echo 'success';
}else{
  echo 'failed';
}
}

UpdateDB();
?>

In testdb_out, shouldnt the include be loaded prior to the function? That works in other programming languages.

Anurag Srivastava
  • 12,230
  • 3
  • 21
  • 36
Lango
  • 243
  • 3
  • 14
  • 1
    If it is outside of function then it is a global variable, and globals are not present by default inside of function scope. Use `global $mysqli;` inside function. – Dharman Mar 08 '19 at 18:52
  • great guys thank you for the prompt replies!!! I though include was by default global and considered in functions. – Lango Mar 08 '19 at 19:03

0 Answers0