What are the advantages of switching from mysql_* to mysqli_* or PDO in PHP?
Switching from mysql_* to mysqli_* or PDO in PHP provides several advantages such as improved security by preventing SQL injection attacks, support for prepared statements for better performance, support for multiple statements, and the ability to use object-oriented programming with mysqli_*.
// Using mysqli_* to connect to a database
$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 SQL query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Fetch data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();