How can the mysql_query() function be utilized to execute SQL queries in PHP for database operations?
To execute SQL queries in PHP for database operations, the mysql_query() function can be utilized. This function takes a SQL query as a parameter and sends it to the MySQL database for execution. The result of the query, such as a result set for SELECT queries or a boolean for INSERT, UPDATE, DELETE queries, can then be processed further in the PHP script.
// Connect to the database
$connection = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $connection);
// Execute a SQL query
$query = "SELECT * FROM table_name";
$result = mysql_query($query);
// Process the result
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
// Process each row
}
} else {
echo "Error executing query: " . mysql_error();
}
// Close the connection
mysql_close($connection);