In what situations should MySQLi or PDO be used instead of mysql_* functions in PHP?
MySQLi or PDO should be used instead of mysql_* functions in PHP when working with databases due to security reasons and better functionality. The mysql_* functions are deprecated and are not recommended for use in modern PHP applications. MySQLi and PDO offer prepared statements that help prevent SQL injection attacks and provide more flexibility in working with different database systems.
// Using MySQLi
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"];
}
} else {
echo "0 results";
}
$mysqli->close();
```
```php
// Using PDO
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
$sql = "SELECT * FROM table";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch()) {
echo "Name: " . $row['name'];
}
$pdo = null;
Keywords
Related Questions
- Are there any best practices for integrating PHP and JavaScript to create dynamic tab functionalities in a web application?
- In PHP, what are the benefits of using partial indexes for database queries that involve filtering by a specific criteria like 'active' status?
- What are the best practices for including files in PHP when they are located in different directories?