What are some alternative methods to mysql_* functions for database interaction in PHP?
The mysql_* functions are deprecated in PHP and have been removed in newer versions. To interact with a database in PHP, it is recommended to use either the MySQLi extension or PDO (PHP Data Objects) for more secure and flexible database operations.
// 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()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"];
}
} else {
echo "0 results";
}
$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);
$stmt = $pdo->query("SELECT * FROM table_name");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"];
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
Keywords
Related Questions
- Are there any best practices for modifying existing PHP modules like the one mentioned in the thread?
- Can variables be passed using POST method in PHP without utilizing a form?
- What are the differences between Model-View-Controller (MVC), Model-View-Presenter (MVP), and Model-View-ViewModel (MVVM) in the context of PHP development?