// Connect to the database $dsn = 'mysql:host=localhost;dbname=mydatabase'; $username = 'myusername'; $password = 'mypassword'; $db = new PDO($dsn, $username, $password); // Query the database $sql = 'SELECT * FROM mytable'; $stmt = $db->query($sql); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Print the results foreach ($results as $row) { echo $row['column1'] . ' ' . $row['column2'] . '
'; }
// Connect to the database $dsn = 'pgsql:host=localhost;dbname=mydatabase'; $username = 'myusername'; $password = 'mypassword'; $db = new PDO($dsn, $username, $password); // Insert a new row into the database $sql = "INSERT INTO mytable (column1, column2) VALUES (:value1, :value2)"; $stmt = $db->prepare($sql); $stmt->bindParam(':value1', $value1); $stmt->bindParam(':value2', $value2); $value1 = 'foo'; $value2 = 'bar'; $stmt->execute(); // Print the number of rows affected echo $stmt->rowCount() . ' rows affected';In this example, we are connecting to a PostgreSQL database and inserting a new row into a table named "mytable". We use prepared statements and bind parameters to avoid SQL injection attacks. The package library used in this example is the PostgreSQL extension for PHP, which provides functions for working with PostgreSQL databases.