How can the PHP code for connecting to a MySQL database be improved for better functionality and security?
Issue: The PHP code for connecting to a MySQL database is vulnerable to SQL injection attacks and lacks error handling. Solution: To improve functionality and security, we can use prepared statements to prevent SQL injection attacks and add error handling to catch any potential issues with the database connection.
<?php
$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);
}
echo "Connected successfully";
// Close connection
$conn->close();
?>
Keywords
Related Questions
- What are the best practices for storing and displaying multi-line text in PHP, considering line breaks and HTML formatting?
- In PHP, what are the advantages and disadvantages of using JavaScript for client-side calculations in a web application like a calculator?
- How can special characters in variable content affect PHP variable passing with paging?