Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

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

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>";
    }
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...