// Database credentials $host = 'localhost'; $username = 'root'; $password = ''; $dbname = 'example_db'; // Connect to database $conn = new mysqli($host, $username, $password, $dbname); // Check for successful connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
// Database credentials $host = 'localhost'; $username = 'root'; $password = ''; $dbname = 'example_db'; // Connect to database try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } // Query the database $stmt = $conn->prepare("SELECT * FROM example_table"); $stmt->execute(); $results = $stmt->fetchAll(PDO::FETCH_ASSOC);This code demonstrates how to query a database using PDO package library. We use a try-catch block to connect to the database and set error mode to exception. We then prepare a SQL statement to select all records from a table using the prepare method. We execute the query using the execute method and retrieve the results using the fetchAll method. We specify the fetch mode as ASSOC to obtain an associative array. In conclusion, the "db" in php refers to database and we use different package libraries such as MySQLi, PDO, etc. to connect to and manipulate databases in php. The examples above demonstrate how to connect to a database using mysqli and query a database using PDO.