What are the recommended alternatives to mysql_ functions in PHP for database interactions?
The recommended alternatives to mysql_ functions in PHP for database interactions are mysqli (MySQL Improved) and PDO (PHP Data Objects). These alternatives provide more secure and flexible options for interacting with databases, as well as better support for prepared statements to prevent SQL injection attacks.
// Using mysqli for database interactions
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Process each row
}
} else {
echo "0 results";
}
$mysqli->close();