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
connection: The MySQLi connection object returned by
mysqli_connect()
. This parameter specifies the connection to the database that will be used for the query.query: The SQL query string to be executed. This can be any valid SQL statement, such as
SELECT
,INSERT
,UPDATE
, orDELETE
.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 amysqli_result
object, which you can use to fetch rows from the result set. - For
INSERT
,UPDATE
, orDELETE
queries,mysqli_query()
returnstrue
on success.
- For
- On failure:
mysqli_query()
returnsfalse
. You can usemysqli_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()
returnsfalse
to handle potential errors. Usemysqli_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.