What are the recommended steps for establishing a database connection, selecting a database, and executing SQL statements in PHP?
Establishing a database connection, selecting a database, and executing SQL statements in PHP involves using the PDO (PHP Data Objects) extension. This extension provides a consistent interface for accessing databases in PHP, allowing you to connect to a database, select a specific database, and execute SQL queries.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Select a specific database
$conn->exec("USE $dbname");
// Execute SQL statements
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
while ($row = $stmt->fetch()) {
echo $row['column_name'] . "<br>";
}
Related Questions
- How can you use MySQL to retrieve data from two columns where one value is repeated and the other is unique?
- What are the advantages and disadvantages of using PHP over Perl for text file searching scripts?
- In the context of web scraping or automation, what considerations should be taken into account when dealing with external resources like Google Analytics or external scripts?