-4

connect_db.php:

<?php
$servername = "1.1.1.1";
$username = "root";
$password = "nope, not making this public :P";
$dbname = "seminarfach";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//$conn = new mysqli(null, $username, $password, $dbname, null, '/cloudsql/seminarfach-abi-links:data');

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "<p>Connected successfully</p>";

// Set charset to UTF-8
if (!$conn->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $conn->error);
    exit();
}

function TuckTheTorld() {
    $conn->close();
}
?>

This is the file that connects to my database, and it is called with require "connect_db.php"; in the file that needs a connection. Now I wanted to create a function that is called to close the connection to the DB. That is the TuckTheTorld function. I named it that to make sure I don't use any keywords or overwirte any other functions.

The problem is that when I call TuckTheTorld() I get the following error:

Fatal error: Call to a member function close() on a non-object in path_to_file\connect_db.php on line 26

Why do I get that error?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
usbpc102
  • 1,137
  • 13
  • 25
  • Yea... first thing that came to my mind somehow... I have no idea why, but I was sure that it will not conflict with anything else... – usbpc102 Nov 25 '15 at 18:43
  • Now that is to long, now that it works I've named it closeConn() to make sense. The name was purly for testing. But I'll name it something more appopriate I ask a question next time. – usbpc102 Nov 25 '15 at 18:48

1 Answers1

0

You need to import the $conn object into the functions namespace by using the global keyword (there is nothing called $conn in the functions namespace because $conn resides in the global files namespace).

Just replace your function with:

function TuckTheTorld() {
    global $conn;
    $conn->close();
}

This should now work for you.

jankal
  • 1,090
  • 1
  • 11
  • 28