How can the use of mysqli_* functions improve the security and efficiency of PHP scripts compared to mysql_* functions?
Using mysqli_* functions can improve the security and efficiency of PHP scripts compared to mysql_* functions because mysqli_* functions support prepared statements, which help prevent SQL injection attacks. Additionally, mysqli_* functions offer better error handling and support for transactions, making it easier to write secure and reliable database queries.
// Connect to database using mysqli
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Example of executing a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "example_username";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process results
}
$stmt->close();
// Close connection
$mysqli->close();