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.

2
  • 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. Commented Mar 8, 2019 at 18:52
  • great guys thank you for the prompt replies!!! I though include was by default global and considered in functions. Commented Mar 8, 2019 at 19:03

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.