What are the differences between the mysql_query and mysqli_query functions in PHP, and when should each be used?

The main difference between mysql_query and mysqli_query functions in PHP is that mysql_query is deprecated as of PHP 5.5.0 and removed as of PHP 7.0.0, while mysqli_query is the improved version that supports the use of prepared statements and provides better security. Therefore, it is recommended to use mysqli_query for new PHP projects to ensure compatibility and security.

// Using mysqli_query to execute a query
$conn = mysqli_connect("localhost", "username", "password", "database");
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);

// Loop through the result set
while ($row = mysqli_fetch_assoc($result)) {
    // Process each row
}

// Close the connection
mysqli_close($conn);