What best practices should be followed when handling database connections and queries in PHP scripts to ensure data integrity?
To ensure data integrity when handling database connections and queries in PHP scripts, it is important to follow best practices such as using prepared statements to prevent SQL injection attacks, validating user input before executing queries, and properly sanitizing data before inserting or updating records in the database.
// Establish a database connection using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
Related Questions
- How can PHP be used to manipulate the placement of elements on a webpage, such as moving links under a specific entry?
- What are the potential reasons for the error "Undefined index: files" in PHP file uploading?
- How can PHP's interpretation of variables impact the execution of functions within a class?