Why is it recommended to avoid using the mysql_* functions in PHP for database interactions?
It is recommended to avoid using the mysql_* functions in PHP for database interactions because they are deprecated as of PHP 5.5 and removed in PHP 7. Instead, developers should use the improved MySQLi (MySQL Improved) or PDO (PHP Data Objects) extensions, which offer better security features, prepared statements to prevent SQL injection attacks, and support for multiple database systems.
// Using MySQLi extension for database interactions
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform a query
$result = $mysqli->query("SELECT * FROM table_name");
// Fetch data
while ($row = $result->fetch_assoc()) {
// Process data
}
// Close connection
$mysqli->close();