How can the deprecated mysql_* functions in PHP be replaced with modern alternatives like mysqli_* or PDO for improved security and functionality?
The deprecated mysql_* functions in PHP should be replaced with modern alternatives like mysqli_* or PDO to improve security and functionality. This is because the mysql_* functions are outdated, lack support for prepared statements, and are vulnerable to SQL injection attacks. By switching to mysqli_* or PDO, developers can utilize features like prepared statements, parameterized queries, and object-oriented interfaces for safer and more efficient database interactions.
// Using mysqli_* functions to connect to a database and perform a query
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform a query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();