What are the recommended alternatives to mysql_* functions in PHP?
The mysql_* functions in PHP are deprecated and have been removed as of PHP 7. Instead, it is recommended to use either mysqli (improved MySQL extension) or PDO (PHP Data Objects) for database operations in PHP.
// Using mysqli
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
// Perform database operations using prepared statements or other secure methods
$mysqli->close();
```
```php
// Using PDO
try {
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Perform database operations using prepared statements or other secure methods
$pdo = null;
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
Related Questions
- Are there best practices for handling 404 errors in PHP to maintain transparency with the client?
- What are the potential pitfalls of using quotation marks in PHP when working with multidimensional arrays?
- What potential pitfalls should be considered when using PHP scripts to redirect image requests and how can they be avoided?