What best practices should be followed when establishing a MySQL connection in PHP?
When establishing a MySQL connection in PHP, it is important to follow best practices to ensure security and efficiency. This includes using secure connection methods, such as PDO or MySQLi, to prevent SQL injection attacks. Additionally, it is recommended to store database credentials in a separate configuration file outside of the web root for added security.
<?php
// Database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Keywords
Related Questions
- Is it considered good practice to include PHP code within HTML tags or should they be kept separate?
- What are some common methods for passing form data in PHP, and what are the potential pitfalls associated with each method?
- What are the advantages and disadvantages of using PHP built-in functions like fputcsv for creating Excel-readable files compared to using external libraries like PHPExcel?