$db_host = "localhost"; $db_user = "username"; $db_password = "password"; $db_name = "database_name"; $db = new mysqli($db_host, $db_user, $db_password, $db_name); if ($db->connect_error) { die("Connection failed: " . $db->connect_error); } // Query the database $result = $db->query("SELECT * FROM table_name"); // Fetch data while ($row = $result->fetch_assoc()) { echo $row['column_name']; } // Close the database connection $db->close();
$db_host = "localhost"; $db_user = "username"; $db_password = "password"; $db_name = "database_name"; $db = new PDO("pgsql:host=$db_host;dbname=$db_name", $db_user, $db_password); // Insert data into table $stmt = $db->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)"); $stmt->bindParam(':value1', $value1); $stmt->bindParam(':value2', $value2); $value1 = "example"; $value2 = "data"; $stmt->execute(); // Close the database connection $db = null;In this example, we're using the PDO package to connect to a PostgreSQL database and insert data into a table. We're using prepared statements to prevent SQL injection attacks. Both of these examples use different package libraries - mysqli and PDO, respectively - which are built-in PHP libraries for connecting to and interacting with databases.