What are the advantages of using mysqli_* or PDO functions over mysql_* functions in PHP for database interactions?
Using mysqli_* or PDO functions over mysql_* functions in PHP for database interactions is recommended because mysql_* functions are deprecated as of PHP 5.5.0 and removed in PHP 7. Additionally, mysqli_* and PDO functions provide better security by supporting prepared statements which help prevent SQL injection attacks. They also offer better support for transactions and multiple database connections.
// Using mysqli_* functions
$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 "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
$mysqli->close();
Keywords
Related Questions
- How can unpack() be used to efficiently split a string into its individual components in PHP?
- What potential pitfalls should be considered when using PHP's image functions to create visual elements like clocks?
- Why is it recommended to develop PHP code locally using tools like XAMPP for better error handling?