The mysqli_query()
function in PHP is used to execute a query against a MySQL database using the MySQLi extension.
🔹 Syntax
mysqli_query(mysqli $connection, string $query, int $resultmode = MYSQLI_STORE_RESULT): mysqli_result|bool
$connection
: A valid connection object (frommysqli_connect()
).$query
: The SQL query to execute (e.g., SELECT, INSERT, UPDATE, DELETE).$resultmode
: Optional. Used for SELECT queries to specify how results are returned (default isMYSQLI_STORE_RESULT
).
🔹 Return Values
- SELECT queries return a
mysqli_result
object on success, orfalse
on failure. - Other queries (INSERT, UPDATE, DELETE, etc.) return
true
on success, orfalse
on failure.
🔹 Examples
✅ Example 1: SELECT Query
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$sql = "SELECT id, name FROM users";
$result = mysqli_query($conn, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
✅ Example 2: INSERT Query
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
✅ Example 3: UPDATE Query
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$sql = "UPDATE users SET name = 'Jane Doe' WHERE id = 1";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
✅ Example 4: DELETE Query
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$sql = "DELETE FROM users WHERE id = 1";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
⚠️ Notes:
- Always sanitize user input to prevent SQL Injection.
- Use
prepared statements
(mysqli_prepare
) for safer queries involving user input.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.