What are the recommended alternatives to the deprecated mysql_* functions in PHP for database queries?
The recommended alternatives to the deprecated mysql_* functions in PHP for database queries are to use either MySQLi (MySQL Improved) or PDO (PHP Data Objects) extensions. These extensions provide improved security features and support for prepared statements, making them more secure and versatile options for interacting with databases in PHP.
// Using MySQLi extension
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
$result = $mysqli->query("SELECT * FROM table_name");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Process the data
}
}
$mysqli->close();
```
```php
// Using PDO extension
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
$statement = $pdo->query("SELECT * FROM table_name");
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
// Process the data
}
$pdo = null;
Related Questions
- What is the best practice for displaying a dropdown menu in a form that retrieves data from a database in PHP?
- In what ways can the configuration settings for sending emails in PHPMailer impact the speed of email delivery?
- What is the recommended method to store and retrieve time data from a MySQL database in PHP?