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
- What are common issues with PHP installations that may cause files to not open correctly?
- What are some alternative approaches to calculating the Unix timestamp for the first day of a specific calendar week in PHP, considering the limitations of the current method?
- What are some security considerations to keep in mind when using PHP to dynamically generate HTML content?