Question

I've seen a few people with this same issue, yet none of the answers solved my problem. This is what I have in three files:

index.php:

 $dbconnect = connectDB("mydb","connect");
 mysqli_query($dbconnect,"INSERT INTO `mytable` (field1,field2) values ('value 1','value 2')");
 connectDB("","kill",$dbconnect);

functions.php

 function connectDB($db_name,$connectorkill,$link) { include('connectDB.inc.php'); }

connectDB.inc.php

 $host="localhost";
 $user="myusername";
 $pass="mypassword";
 if($connectorkill == "connect") {  
 if($dblink = mysqli_connect($host, $user, $pass, $db_name)) {
 echo "dblink created.";
  return $dblink;
 } else { echo "Error connecting to database."; }  
 } elseif($connectorkill == "kill") { mysqli_close($link); }

and what I get is:

 Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/username/public_html/members/index.php on line 2

which looks like the connectDB function is not doing its job, specifically the return of the $dblink variable in connectDB.inc.php. I went ahead and moved the code from connectDB.inc.php to inside the functions.php and it solved the problem, but I don't want it set up that way. Is there a way to solve this error?

Was it helpful?

Solution

Two solutions:

Solution 1: Refractor your code, something along the lines of:

config.php:

$config = array(
    "databases" => array(
        "my_database" => array(
            "host"  =>  "localhost",
            "user"  =>  "myusername",
            "pass"  =>  "mypassword"
        )
    )
);

functions.php:

require("config.php");

function connectDB($dbname)
{
    global $config;

    if (!isset($config["databases"][$dbname]))
        return; // error, database info not in $config

    $dbc = $config["databases"][$dbname];

    $dbcon = mysqli_connect($dbc["host"], $dbc["user"], $dbc["pass"], $dbname);
    if (!$dbcon)
        return; // unable to connect error goes here

    return $dbcon;
}

Note that this is just the bare minimum of a connectDB function. There really should be more error checking in there (for example, on each of the $dbc keys. It also needs proper error reporting and such, this is just a general hint in the right direction.

Solution 2: Add return in front of your include...

function connectDB($db_name,$connectorkill,$link) { return include('connectDB.inc.php'); }

Regardless of the solution: You really need some error checking code in your index.php because no matter what you do: Your connectDB function isn't always going to return a valid database connection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top