PHP MySQL mysqli_query() function


The mysqli_query() function in PHP is used to execute SQL queries against a MySQL database when using the MySQLi extension in procedural style. Here's a detailed explanation:

Syntax

mysqli_query(connection, query, resultmode)

Parameters

  1. connection: The MySQLi connection object returned by mysqli_connect(). This parameter specifies the connection to the database that will be used for the query.

  2. query: The SQL query string to be executed. This can be any valid SQL statement, such as SELECT, INSERT, UPDATE, or DELETE.

  3. resultmode (optional): This parameter specifies the type of result to return. The possible values are:

    • MYSQLI_STORE_RESULT (default): The result set is stored in memory.
    • MYSQLI_USE_RESULT: The result set is fetched directly from the database server, which can be more efficient for large result sets.

Return Values

  • On success:
    • For SELECT queries, mysqli_query() returns a mysqli_result object, which you can use to fetch rows from the result set.
    • For INSERT, UPDATE, or DELETE queries, mysqli_query() returns true on success.
  • On failure:
    • mysqli_query() returns false. You can use mysqli_error() to get a description of the error.

Example

1. Executing a SELECT Query

<?php
// Step 1: Connect to the database $conn = mysqli_connect('localhost', 'username', 'password', 'database'); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Step 2: Prepare and execute a SELECT query $sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql); if ($result) { // Fetch and display rows while ($row = mysqli_fetch_assoc($result)) { echo "Username: " . $row['username'] . " - Email: " . $row['email'] . "<br>"; } // Free the result set mysqli_free_result($result); } else { echo "Error: " . mysqli_error($conn); } // Step 3: Close the connection mysqli_close($conn); ?>

2. Executing an INSERT, UPDATE, or DELETE Query

<?php
// Step 1: Connect to the database $conn = mysqli_connect('localhost', 'username', 'password', 'database'); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Step 2: Prepare and execute an INSERT query $sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . mysqli_error($conn); } // Step 3: Close the connection mysqli_close($conn); ?>

Notes

  • Error Handling: Always check if mysqli_query() returns false to handle potential errors. Use mysqli_error() to get the error message.
  • Security: To avoid SQL injection, especially when using user inputs in queries, use mysqli_real_escape_string() to escape special characters, or use prepared statements.