0

I've been searching stack to get my answer, but nothing fixed my problem. So here's my shot:

$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
function GetArticle() {
  global $conn;
  $sql = "sql query";
  $getresult = mysqli_query($conn, $sql);
  ..
}

This doesn't seem to work. If I put $conn inside the function, it works fine.

Any ideas?

5
  • 1
    How'd you know the $conn = assignment actually resided in the global scope? Commented Apr 29, 2015 at 19:20
  • Yes, if you put that as is in a file it should work. Commented Apr 29, 2015 at 19:21
  • Hey mario, i've tried to use a simple variable and return it by the function with the global, worked fine. only the database connection wont work Commented Apr 29, 2015 at 19:22
  • Going off of @AbraCadaver the best thing would be to put your connection code in a separate file and include that connection file in future files( which connect to the a db ) Commented Apr 29, 2015 at 19:34
  • Try to get error with mysqli_connect_error() or mysqli_error(). Maybe you closed connection somewhere above or did not use mysqli_free_result() in some of your previous queries. Commented Apr 29, 2015 at 21:36

1 Answer 1

2

I don't know your exact situation, but in general I do not see the benefit to using $conn as global. Your function depends on a mysqli connection in order to work, so just make the connection a function parameter.

function GetArticle($conn) {
  $sql = "sql query";
  $getresult = mysqli_query($conn, $sql);
  ..
}

Then after you have established your connection, you can call the function with your connection object as its argument.

$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
$article = GetArticle($conn);

I think this is a more manageable approach than trying to keep track of whether $conn is available in global scope before calling the function.

Sign up to request clarification or add additional context in comments.

2 Comments

it's that i have all my functions in one php file. but anyway, i fixed it by using mysql instead mysqli
I remember once in an apartment I was renting, I asked the management to fix one of the bedroom doors that was hung at a slight angle, which prevented it from closing properly and left a sizable gap above the top corner. The maintenance guy fixed it by sawing off the bottom corner of the door.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.