Skip to content
PHP Logo

What is the significance of passing a mysqli object as the first parameter in mysqli_query() function?

Passing a mysqli object as the first parameter in mysqli_query() function is significant because it establishes a connection to the MySQL database. Without this connection, the query cannot be executed. By passing the mysqli object, the function knows which database connection to use when executing the query.

php
// Create a mysqli object and establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Execute a query using the mysqli_query() function
$result = mysqli_query($mysqli, "SELECT * FROM table_name");

// Use the result as needed
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}

// Close the connection
$mysqli->close();