What are the best practices for establishing a database connection and querying data in PHP?
Establishing a database connection and querying data in PHP involves using the PDO (PHP Data Objects) extension for secure, efficient database access. To establish a connection, you need to create a PDO object with the database credentials. To query data, you can prepare a SQL statement, bind parameters if needed, execute the query, and fetch the results.
// Establishing a database connection
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// Querying data
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$id = 1;
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo $row['username'] . '<br>';
}
Related Questions
- What are some best practices for prefilling form fields in PHP based on database values?
- What additional features or parameters should be considered when designing a function to generate HTML select elements in PHP for practical use?
- What potential issue arises when using the same variable for both htmlspecialchars and nl2br functions in PHP?