What is the purpose of the mysql_query function in PHP when working with MySQL databases?
The mysql_query function in PHP is used to send a query to the MySQL database for execution. It is commonly used to perform SELECT, INSERT, UPDATE, DELETE, or other SQL operations on the database. This function returns a resource if the query was successful, or false if it failed. It is important to note that the mysql_query function is deprecated in newer versions of PHP and should be replaced with mysqli_query or PDO.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Perform a query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Process the result
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
mysqli_close($connection);
Related Questions
- Why does the order of applying htmlspecialchars and nl2br matter in PHP when outputting text?
- What are the potential issues with using PHP for controlling relays on a website, especially for beginners?
- Can the use of .htaccess for password protection in PHP impact the performance of the website or application?