19

I am trying to build a simple custom CMS, but I'm getting an error:

Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in

Why am I getting this error? All my code is already MySQLi and I am using two parameters, not one.

$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

//check connection
if (mysqli_connect_errno($con))
{
    echo "Failed to connect to MySQL:" . mysqli_connect_error();
}

function getPosts() {
    $query = mysqli_query($con,"SELECT * FROM Blog");
    while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Philip
  • 569
  • 2
  • 5
  • 27

3 Answers3

30

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.

You should pass your connection object in as a dependency, eg

function getPosts(mysqli $con) {
    // etc

I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

getPosts($con);
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    so this is unneed in mysql? for some reason this only happens with mysqli? – Philip Sep 18 '13 at 02:12
  • 4
    The (deprecated) MySQL extension would use the last known connection if the `$link_identifier` argument was not passed in to functions like `mysql_query`. The MySQLi extension offers no such convenience. – Phil Sep 18 '13 at 02:16
11

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}
user3169490
  • 163
  • 1
  • 8
0

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

staticsan
  • 29,935
  • 4
  • 60
  • 73