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

前端 未结 3 1120
醉话见心
醉话见心 2020-11-22 11:49

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

相关标签:
3条回答
  • 2020-11-22 12:17

    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>";
        }
    }
    
    0 讨论(0)
  • 2020-11-22 12:19

    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);
    
    0 讨论(0)
  • 2020-11-22 12:21

    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.

    0 讨论(0)
提交回复
热议问题