You are on page 1of 34

PostgreSQL Tutorial

CSE-6001 PostgreSQL Tutorial

Table of Contents
Basics of PostgreSQL............................................................................................................................................3
What is PostgreSQL?..........................................................................................................................................................3
Tutorial Overview...............................................................................................................................................................3
PostgreSQL Features......................................................................................................................................................... 3
PostgreSQL Database Administration........................................................................................................................5
psql....................................................................................................................................................................................5
phpPgAdmin................................................................................................................................................................. 5
pgAdmin......................................................................................................................................................................... 5
Advantages of PostgreSQL.............................................................................................................................................. 6
Disadvantages of PostgreSQL........................................................................................................................................ 6
PostgreSQL Download and Installation.........................................................................................................7
PostgreSQL Installation on Windows.........................................................................................................................7
PostgreSQL Installation on Mac....................................................................................................................................9
Managing Databases in PostgreSQL............................................................................................................. 11
Getting up and Running with PostgreSQL............................................................................................................. 11
Connect to a PostgreSQL Server................................................................................................................................ 11
PostgreSQL Create DB.................................................................................................................................................... 12
PostgreSQL Creating a Table....................................................................................................................................... 14
CRUD Operations in PostgreSQL................................................................................................................... 17
Creating or Inserting some records into the newly created table -............................................................17
Reading/viewing the data from the table -...........................................................................................................18
Updating a record in the table -................................................................................................................................. 19
Deleting a record in the table -...................................................................................................................................19
PostgreSQL CRUD in PHP................................................................................................................................. 21
Index Page........................................................................................................................................................................... 21
Create.................................................................................................................................................................................... 25
Read....................................................................................................................................................................................... 27
Update...................................................................................................................................................................................29
Delete.................................................................................................................................................................................... 32
PostgreSQL CRUD in Python........................................................................................................................... 35

CSE-6001 Advanced Database Systems | United International University 1


PostgreSQL Tutorial

Understanding PostgreSQL..........................................................................................................................................35
Understanding psycopg2..............................................................................................................................................35
Connecting Python to PostgreSQL............................................................................................................................ 35
Creating a table in PostgreSQL................................................................................................................................... 35
Executing Basic PostgreSQL Queries in Python.................................................................................................. 35
Advanced PostgreSQL Queries in Python.............................................................................................................. 35
Getting Started with SQLAlchemy.............................................................................................................................36

CSE-6001 Advanced Database Systems | United International University 2


PostgreSQL Tutorial

Basics of PostgreSQL

What is PostgreSQL?
PostgreSQL is a lightweight and open-source RDBMS (Relational Database Management System). It
is extremely well accepted by the industry.

Tutorial Overview
In this tutorial, we are going to start with the installation of PostgreSQL. Then, we will learn
beginner-level topics of PostgreSQL language, such as creating a database, dropping a database,
selecting a database, selecting a table, updating a record, creating a table, deleting a record,
dropping a table, inserting a record, etc. Finally, we will implement Create, Read, Update and Delete
(CRUD) operations using a scripting language (e.g., Python or PHP).

PostgreSQL Features
It is one of the most popular databases supporting JSON (non-relational) and SQL for (relational)
queries. PostgreSQL is an object-relational database management system (ORDBMS). It contains
various advanced data types and robust feature sets, increasing the software's extensibility,
reliability, and integrity.

PostgreSQL includes multiple features designed to help the developers to develop the applications,
manage our data in the datasets, and managers can keep the data integrity and create Risk-tolerant
environments. Whenever a new release comes into the market, the PostgreSQL Global group of
developers will enhance the previous features and adds some new features based on the user's
demand.

The essential features of PostgreSQL are as follows:

Free to download: It is open-source, and we can easily download it from the official website of
PostgreSQL.

Compatible with several operation systems: PostgreSQL runs on all major operating systems
such as Microsoft Windows, Linux, MacOS X, UNIX (AIX, BSD, HP-UX, SGI IRIX, Solaris, and Tru64),
etc.

CSE-6001 Advanced Database Systems | United International University 3


PostgreSQL Tutorial

Compatible with various programming languages: It supports multiple programming interfaces


such asC/C++, JAVA, Python, Perl, Ruby, Tcl, and ODBC (Open Database Connectivity).

Compatible with Data Integrity: It supports data integrity which includes the following:

● Primary Keys
● UNIQUE, NOT NULL
● Foreign Keys
● Explicit Locks, Advisory Locks
● Exclusion Constraints

Support multiple features of SQL: PostgreSQL supports various features of SQL, which include the
followings:

● MVCC (Multi-Version Concurrency Control).


● It supports multiple Indexing such as Multicolumn, Partial, B-tree, and expressions.
● SQL sub-selects.
● Complex SQL queries.
● Streaming Replication
● It supports transactions, Nested Transactions through Savepoints.
● Just-in-time compilation of expressions
● Table partitioning

Compatible with multiple data types: PostgreSQL support various data types, such as:

● Structured: Array, Date and Time, UUID (Universally Unique Identifier), Array, Range.
● Primitives: String, Integer, Boolean, Numeric.
● Customizations: Custom Types, Composite.
● Geometry: Polygon, Circle, Line, Point,
● Document: XML, JSON/JSONB, Key-value.

Highly extensible: PostgreSQL is highly extensible in several phases, which are as follows:

● It supports procedural Languages such as Perl, PL/PGSQL, Python, etc.


● JSON/SQL path expressions
● Stored procedures and functions.
● For tables, it supports a customizable storage interface.
● It is compatible with foreign data wrappers, connecting different databases with a standard
SQL interface.

Secure: It is safe because it follows several security aspects, which are as follows:

● PostgreSQL provides a robust access control system.

CSE-6001 Advanced Database Systems | United International University 4


PostgreSQL Tutorial

● It includes several Authentications such as Lightweight Directory Access Protocol(LDAP),


Generic Security Service Application Program Interface (GSSAPI), SCRAM-SHA-256, Security
Support Provider Interface (SSPI), Certificate, and so on.
● PostgreSQL supports Column and row-level security.

Highly Reliable: It is highly reliable and also provides disaster recovery such as:

● Active standbys, PITR (Point in time recovery)


● It supports WAL (Write-ahead Logging)
● Tablespaces
● It supports different types of Replicationlike Synchronous, Asynchronous, and Logical.

PostgreSQL Database Administration


The PostgreSQL database administration covers the essential PostgreSQL database server
administration actions. We have several open sources and paid tools available in the market. Let us
understand some of the most commonly used database management tools of PostgreSQL:

psql
It is a terminal-based front-end command-line tool; where we can directly enter the SQL queries or
run them from a file and we can also see the query results. It offers us many Meta commands and
several shells, such as automating extensive ranges of tasks and facilitating writing scripts.

phpPgAdmin
It is a web-based management tool for PostgreSQL and is built on the phpMyAdmin interface, which
was initially written for MySQL administration. The phpPgAdmin is written in PHP programming
language. It can be configured easily and provides simple data manipulation. It keeps up the slony
master-slave replication machine and is available in 27 languages. Here, we can import the SQL
scripts and Copy the data.

pgAdmin
It is one of PostgreSQL's most famous and open-source management and development platforms. It
can be used on various operating systems such as UNIX, Linux, Mac OS X, and Windows to achieve
PostgreSQL 9.2 and above versions.

CSE-6001 Advanced Database Systems | United International University 5


PostgreSQL Tutorial

Advantages of PostgreSQL
The benefits of PostgreSQL are as follows:

● PostgreSQL is easy to use, so we do not require much training.


● It requires low maintenance management for enterprise as well as embedded usage.
● PostgreSQL manages data in a relational database, which is very powerful and robust.
● We can quickly get the source code of PostgreSQL as it is freely available in an open-source
license, and we can immediately implement changes according to our requirements.
● It can execute dynamic web applications and websites as the LAMP stack option.
● PostgreSQL is a highly risk-tolerant database.

Disadvantages of PostgreSQL
The drawbacks of PostgreSQL are as follows:

● PostgreSQL does not support the various open-source applications as compared to MySQL.
● Creating replication is a bit complex.
● It is not maintained by one company.
● PostgreSQL speed performance is not as good as compared to different tools.
● It is slow compared to MySQL.
● Sometimes, the installation process is not easy for the learner.

CSE-6001 Advanced Database Systems | United International University 6


PostgreSQL Tutorial

PostgreSQL Download and Installation

Note: While you are installing PostgreSQL take note of the password and port number that you are
entering.

PostgreSQL Installation on Windows


To install and run PostgreSQL on a Mac, you can follow these steps:

1. Download PostgreSQL: Visit the official PostgreSQL website (https://www.postgresql.org/)


and go to the download page.

2. Select the Version: Choose the version of PostgreSQL you want to install. It is generally
recommended to select the latest stable version available.

3. Choose the Windows Platform: On the download page, scroll down to the Windows section
and select the Windows version that matches your operating system (32-bit or 64-bit).

4. Download the Installer: Click on the download link for the Windows installer package. The
installer package will have a name similar to "postgresql-[version]-[platform].exe".

5. Run the Installer: Once the download is complete, locate the downloaded installer package
and double-click it to start the installation process.

6. Follow the Installation Steps: The PostgreSQL installer will guide you through the
installation process. Follow the on-screen instructions and review and accept the license
agreement.

7. Choose the Installation Directory: During the installation, you will be prompted to select the
installation directory for PostgreSQL. You can choose the default directory or specify a
different one according to your preference.

8. Set the Password: During the installation process, you will also be prompted to set a
password for the PostgreSQL superuser (usually called "postgres"). This password is
important for accessing and managing the PostgreSQL database.

CSE-6001 Advanced Database Systems | United International University 7


PostgreSQL Tutorial

9. Choose the Components: In the component selection screen, you can choose the specific
components you want to install. By default, all components are selected, which is
recommended for most cases.

10. Select the Data Directory: The installer will ask you to select a data directory where
PostgreSQL will store its database files. You can choose the default location or specify a
different one if needed.

11. Complete the Installation: Once you have selected the desired options, click the "Next" or
"Install" button to start the installation. The installer will copy the necessary files and
complete the installation process.

12. Start PostgreSQL: After the installation is complete, you will be prompted to start the
PostgreSQL service. Ensure the "Launch Stack Builder at exit" option is checked and click
"Finish". This will open the Stack Builder utility.

13. Stack Builder Utility: In the Stack Builder utility, you can choose additional components,
extensions, or updates for PostgreSQL. You can skip this step for now and close the utility.

14. Verify the Installation: To verify that PostgreSQL is running, you can open the "pgAdmin"
tool. It should be available in the Start menu or you can search for it. Once opened, you
should see the PostgreSQL server listed in the server dashboard.

Congratulations! You have successfully installed PostgreSQL on your Windows system. You can now
use tools like pgAdmin or connect to the PostgreSQL server using SQL clients to interact with
databases and perform database operations.

Note: It is important to keep your PostgreSQL installation up to date with the latest security patches
and updates. Regularly check for updates on the PostgreSQL website and follow the recommended
upgrade process when new versions are released.

CSE-6001 Advanced Database Systems | United International University 8


PostgreSQL Tutorial

PostgreSQL Installation on Mac


To install and run PostgreSQL on a Mac, you can follow these steps:

1. Download PostgreSQL: Visit the official PostgreSQL website (https://www.postgresql.org/)


and navigate to the download page.

2. Select the Version: Choose the version of PostgreSQL you want to install. Typically, it's
recommended to select the latest stable version available.

3. Choose the macOS Platform: On the download page, scroll down to the macOS section and
select the macOS version that corresponds to your operating system.

4. Download the Installer: Click on the download link for the macOS installer package. The
installer package will have a name similar to "postgresql-[version]-[platform].dmg".

5. Run the Installer: Once the download is complete, locate the downloaded installer package
in your Downloads folder or the specified download location. Double-click the installer
package to start the installation process.

6. Follow the Installation Steps: The PostgreSQL installer will guide you through the
installation process. Follow the on-screen instructions, and make sure to review and accept
the license agreement.

7. Choose the Installation Type: During the installation, you will be prompted to choose the
installation type. Select the PostgreSQL installation option to install the PostgreSQL
database server.

8. Set the Password: During the installation process, you will also be prompted to set a
password for the PostgreSQL superuser (usually called "postgres"). This password is
important for accessing and managing the PostgreSQL database.

9. Complete the Installation: Once the installation is complete, you can exit the installer.

10. Start PostgreSQL: To start PostgreSQL, open the "Terminal" application on your Mac. You can
find it in the "Applications" folder under "Utilities". In the Terminal, type the following
command and press Enter:
pg_ctl -D /usr/local/var/postgres start
This command starts the PostgreSQL database server.

11. Verify the Installation: To verify that PostgreSQL is running, you can enter the following
command in the Terminal:
ps auxwww | grep postgres

CSE-6001 Advanced Database Systems | United International University 9


PostgreSQL Tutorial

If PostgreSQL is running properly, you should see several lines of output related to the
PostgreSQL server processes.

Congratulations! You have successfully installed and started PostgreSQL on your Mac. You can now
begin using PostgreSQL and interacting with databases using SQL queries.

Note: It's important to keep your PostgreSQL installation up to date with the latest security patches
and updates. Regularly check for updates on the PostgreSQL website and follow the recommended
upgrade process when new versions are released.

CSE-6001 Advanced Database Systems | United International University 10


PostgreSQL Tutorial

Managing Databases in PostgreSQL

Getting up and Running with PostgreSQL


Once you have installed PostgreSQL successfully on your machine, open up pgAdmin. pgAdmin is a
handy utility which comes with the PostgreSQL installation, and it lets you do regular
database-related tasks through an excellent graphical interface. Once you open it, it will ask for the
Master Password you set.

Connect to a PostgreSQL Server


After entering the password, you will see a server named "PostgreSQL 15" enlisted in the interface.
Connect to the server by entering the password that you gave during the installation. Your version
may differ from the above and so does the port number (5432). Once you have successfully
connected to the local database server, you will get an interface similar to the following -

CSE-6001 Advanced Database Systems | United International University 11


PostgreSQL Tutorial

PostgreSQL Create DB
Your first task will be to create a database, and you can do so by right-clicking on the Databases tab
and then selecting New Database from the drop-down options. Let's create a database named
UIU_Courses.

CSE-6001 Advanced Database Systems | United International University 12


PostgreSQL Tutorial

On the SQL tab of the Create Database popup window you can see the SQL code for creating the
database.

CREATE DATABASE "UIU_Courses"

WITH

OWNER = postgres

ENCODING = 'UTF8'

CONNECTION LIMIT = -1

IS_TEMPLATE = False;

CSE-6001 Advanced Database Systems | United International University 13


PostgreSQL Tutorial

Once the database is created, you can proceed with the next sections of this tutorial.

PostgreSQL Creating a Table


To be able to operate on a database, you will need a table. So let's go ahead and create a simple table
(also called a relation) named courses with the following specification (schema) -

CSE-6001 Advanced Database Systems | United International University 14


PostgreSQL Tutorial

The specification gives us quite a little information on the columns of the table -

● The table's primary key should be course_id (note that only this one is bold) and its data
type should be an integer. A primary key is a constraint which enforces the column values to
be non-null and unique. It lets you uniquely identify a specific set of instances present in the
table.
● The rest of the information in the specification should be easy to interpret now.

To create a table, right-click on the newly created database UIU_Courses and select CREATE Script
from the options. You should get something similar to the following -

Let's execute the following query now -

CREATE TABLE courses (

course_id SERIAL PRIMARY KEY UNIQUE,

course_name VARCHAR (50) UNIQUE NOT NULL,

course_faculty VARCHAR (100) NOT NULL,

topics TEXT NOT NULL

CSE-6001 Advanced Database Systems | United International University 15


PostgreSQL Tutorial

);

The general structure of a table creation query in PostgreSQL looks like this -

CREATE TABLE table_name (

column_name TYPE column_constraint,

table_constraint table_constraint

We did not specify any table constraints while creating the table. That can be avoided for now.
Everything else is quite readable except for the keyword SERIAL. Serial in PostgreSQL lets you
create an auto-increment column. By default, it creates values of type integer. Serial frees us from
the burden of remembering the last inserted/updated primary key of a table, and it is a good
practice to use auto-increments for primary keys.

CSE-6001 Advanced Database Systems | United International University 16


PostgreSQL Tutorial

CRUD Operations in PostgreSQL

Creating or Inserting some records into the newly created table -


In this step, you will insert some records into the table. Your records should contain the following -

● A course name
● Faculty's name
● Course topic

The values for the column course_id will be handled by PostgreSQL itself. The general structure of
an insert query in PostgreSQL looks like this -

INSERT INTO table(column1, column2, …)


VALUES(value1, value2, …);

Let's insert some records -

INSERT INTO courses(course_name, course_faculty, topics)


VALUES('Software Quality Management','Prof. Dr. Hasan Sarwar','To be
declared later.');

INSERT INTO courses(course_name, course_faculty, topics)


VALUES('Advanced Database Systems','Dr. Md. Saddam Hossain
Mukta','Database system architecture; managing storage;');

INSERT INTO courses(course_name, course_faculty, topics)


VALUES('Information Technology Audit and Assessment','Dr. Suman
Ahmmed','Generally Accepted Auditing Standards (GAAS); Phases of an IT
Audit: Establish the Terms of the Engagement, Preliminary Review,
Establish Materiality and Assess Risks, Plan the Audit, Consider
Internal Control, Perform Audit Procedures, Issue the Audit Report…');

Note that you did not specify the primary keys explicitly. You will see its effects in a moment.

When you execute the above two queries, you should get the following result upon successful
insertions -

CSE-6001 Advanced Database Systems | United International University 17


PostgreSQL Tutorial

INSERT 0 1
Query returned successfully in 40 msec.

Reading/viewing the data from the table -


You will probably do this a lot in your data science journey. For now, let's see how is the table
datacamp_courses holding up.

This is generally called a select query, and the generic structure of a select query looks like this -

SELECT
column_1,
column_2,
...
FROM
table_name;

Let's select all the columns from the table courses

SELECT * FROM courses;

And you get -

If you want just to see the names of the courses, you can do so by -

SELECT course_name from courses;

CSE-6001 Advanced Database Systems | United International University 18


PostgreSQL Tutorial

And you get -

Updating a record in the table -


The general structure of an update query in SQL looks like the following:

UPDATE table
SET column1 = value1,
column2 = value2 ,...
WHERE
condition;

You will update the record where course_faculty = "Dr. Md. Saddam Hossain Mukta" and set the
course_name to "CSE-6001 Advanced Database Systems". You will then verify if the record is
updated. The query for doing this would be -

UPDATE courses SET course_name = 'CSE-6001 Advanced Database Systems'


WHERE course_faculty = 'Dr. Md. Saddam Hossain Mukta';

Let's see if your update query had the intended effect by running a select query -

SELECT * FROM courses;

Deleting a record in the table -


The general structure of a delete query in SQL looks like the following:

CSE-6001 Advanced Database Systems | United International University 19


PostgreSQL Tutorial

DELETE FROM table


WHERE condition;

You are going to delete the record where course_name = "Deep Learning in Python" and then verify
if the record is deleted. Following the structure, you can see that the following query should be able
to do this -

DELETE from courses


WHERE course_name = 'CSE-6001 Advanced Database Systems';

Keep in mind that the keywords are not case-sensitive in SQL, but the data is case-sensitive. This is
why you see a mixture of upper and lower case in the queries.

CSE-6001 Advanced Database Systems | United International University 20


PostgreSQL Tutorial

PostgreSQL CRUD in PHP

Index Page

<!DOCTYPE html>

<html>

<head>

<title>CRUD Operations with PHP and PostgreSQL</title>

<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap
.min.css" rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK
2Kadq2F9CUG65" crossorigin="anonymous">

<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.b
undle.min.js"
integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYX
K/7HAuoJl+0I4" crossorigin="anonymous"></script>

</head>

<body>

<div class="container mt-4">

<h2 class="mb-4">CRUD Operations with PHP and PostgreSQL</h2>

<!-- Create Operation -->

<h4>Create Data</h4>

<form method="POST" action="create.php">

CSE-6001 Advanced Database Systems | United International University 21


PostgreSQL Tutorial

<div class="mb-3">

<label for="column1" class="form-label">Course


Name</label>

<input type="text" class="form-control" name="course_name"


placeholder="Course Name" required>

</div>

<div class="mb-3">

<label for="column2" class="form-label">Course


Faculty</label>

<input type="text" class="form-control"


name="course_faculty" placeholder="Course Faculty" required>

</div>

<div class="mb-3">

<label for="column2" class="form-label">Topics</label>

<input type="text" class="form-control" name="topics"


placeholder="Topics" required>

</div>

<button type="submit" class="btn btn-primary">Create</button>

</form>

<!-- Read Operation -->

<h4 class="mt-4">Read Data</h4>

<table class="table">

<thead>

<tr>

<th>ID</th>

CSE-6001 Advanced Database Systems | United International University 22


PostgreSQL Tutorial

<th>Course Name</th>

<th>Course Faculty</th>

<th>Topics</th>

<th>Actions</th>

</tr>

</thead>

<tbody>

<?php

// Database connection settings

$host = 'localhost';

$dbname = 'UIU_Courses';

$user = 'postgres';

$password = 'cse6001';

// Establish a database connection using PDO

try {

$dsn = "pgsql:host=$host;dbname=$dbname";

$pdo = new PDO($dsn, $user, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

echo "Connection failed: " . $e->getMessage();

die();

CSE-6001 Advanced Database Systems | United International University 23


PostgreSQL Tutorial

// Perform the select operation using PDO

$query = "SELECT * FROM courses";

$stmt = $pdo->query($query);

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

echo "<tr>";

echo "<td>{$row['course_id']}</td>";

echo "<td>{$row['course_name']}</td>";

echo "<td>{$row['course_faculty']}</td>";

echo "<td>{$row['topics']}</td>";

echo "<td><a href='update.php?id={$row['course_id']}'


class='btn btn-sm btn-warning'>Edit</a> <form method='POST'
action='delete.php'><input type='hidden' name='course_id'
value='{$row['course_id']}'><button type='submit' class='btn btn-sm
btn-danger'>Delete</button></form> </td>";

echo "</tr>";

// Close the database connection

$pdo = null;

?>

</tbody>

</table>

</div>

</body>

</html>

CSE-6001 Advanced Database Systems | United International University 24


PostgreSQL Tutorial

Create

<?php

// Database connection settings

$host = 'localhost';

$dbname = 'UIU_Courses';

$user = 'postgres';

$password = 'cse6001';

// Establish a database connection using PDO

try {

$dsn = "pgsql:host=$host;dbname=$dbname";

$pdo = new PDO($dsn, $user, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

echo "Connection failed: " . $e->getMessage();

die();

// Check if the form is submitted

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

// Retrieve form data

$course_name = $_POST['course_name'];

CSE-6001 Advanced Database Systems | United International University 25


PostgreSQL Tutorial

$course_faculty = $_POST['course_faculty'];

$topics = $_POST['topics'];

// Perform the insert operation using PDO prepared statements

try {

$query = "INSERT INTO courses (course_name, course_faculty,


topics) VALUES (:column1, :column2, :column3)";

$stmt = $pdo->prepare($query);

// Bind the values to the prepared statement

$stmt->bindValue(':column1', $course_name);

$stmt->bindValue(':column2', $course_faculty);

$stmt->bindValue(':column3', $topics);

// Execute the prepared statement

$stmt->execute();

echo "Data inserted successfully!";

} catch (PDOException $e) {

echo "Insert operation failed: " . $e->getMessage();

die();

// Close the database connection

CSE-6001 Advanced Database Systems | United International University 26


PostgreSQL Tutorial

$pdo = null;

?>

<!-- HTML form for creating data -->

<form method="POST" action="create.php">

<input type="text" name="course_name" placeholder="Course Name"


required>

<input type="text" name="course_faculty" placeholder="Course


Faculty" required>

<input type="text" name="topics" placeholder="Topics" required>

<button type="submit">Create</button>

</form>

Read

<?php

// Database connection settings

$host = 'localhost';

$dbname = 'UIU_Courses';

$user = 'postgres';

$password = 'cse6001';

// Establish a database connection using PDO

try {

CSE-6001 Advanced Database Systems | United International University 27


PostgreSQL Tutorial

$dsn = "pgsql:host=$host;dbname=$dbname";

$pdo = new PDO($dsn, $user, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

echo "Connection failed: " . $e->getMessage();

die();

// Perform a database query using PDO

try {

$query = "SELECT * FROM courses";

$stmt = $pdo->query($query);

// Fetch results as an associative array

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process and display the results

foreach ($results as $row) {

echo "Course ID: " . $row['course_id'] . "<br>";

echo "Course Name: " . $row['course_name'] . "<br>";

echo "Course Faculty: " . $row['course_faculty'] . "<br>";

echo "<br>";

} catch (PDOException $e) {

CSE-6001 Advanced Database Systems | United International University 28


PostgreSQL Tutorial

echo "Query failed: " . $e->getMessage();

die();

// Close the database connection

$pdo = null;

?>

Update

<?php

// Database connection settings

$host = 'localhost';

$dbname = 'UIU_Courses';

$user = 'postgres';

$password = 'cse6001';

// Establish a database connection using PDO

try {

$dsn = "pgsql:host=$host;dbname=$dbname";

$pdo = new PDO($dsn, $user, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

CSE-6001 Advanced Database Systems | United International University 29


PostgreSQL Tutorial

echo "Connection failed: " . $e->getMessage();

die();

// Check if the form is submitted

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

// Retrieve form data

$id = $_POST['course_id'];

$course_name = $_POST['course_name'];

$course_faculty = $_POST['course_faculty'];

$topics = $_POST['topics'];

// Perform the update operation using PDO prepared statements

try {

$query = "UPDATE courses SET course_name = :column1,


course_faculty = :column2, topics = :column3 WHERE course_id = :id";

$stmt = $pdo->prepare($query);

// Bind the values to the prepared statement

$stmt->bindValue(':column1', $course_name);

$stmt->bindValue(':column2', $course_faculty);

$stmt->bindValue(':column3', $topics);

$stmt->bindValue(':id', $id);

// Execute the prepared statement

CSE-6001 Advanced Database Systems | United International University 30


PostgreSQL Tutorial

$stmt->execute();

echo "Data updated successfully!";

} catch (PDOException $e) {

echo "Update operation failed: " . $e->getMessage();

die();

// Close the database connection

$pdo = null;

?>

<!-- HTML form for updating data -->

<form method="POST" action="update.php">

<input type="number" name="course_id" value={$row['course_id']}>


<!-- Replace with appropriate input for the ID -->

<input type="text" name="course_name" placeholder="Course Name"


required>

<input type="text" name="course_faculty" placeholder="Course


Faculty" required>

<input type="text" name="topics" placeholder="Topics" required>

<button type="submit">Update</button>

</form>

CSE-6001 Advanced Database Systems | United International University 31


PostgreSQL Tutorial

Delete

<?php

// Database connection settings

$host = 'localhost';

$dbname = 'UIU_Courses';

$user = 'postgres';

$password = 'cse6001';

// Establish a database connection using PDO

try {

$dsn = "pgsql:host=$host;dbname=$dbname";

$pdo = new PDO($dsn, $user, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

echo "Connection failed: " . $e->getMessage();

die();

// Check if the form is submitted

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

// Retrieve form data

$id = $_POST['course_id'];

CSE-6001 Advanced Database Systems | United International University 32


PostgreSQL Tutorial

// Perform the delete operation using PDO prepared statements

try {

$query = "DELETE FROM courses WHERE course_id = :id";

$stmt = $pdo->prepare($query);

// Bind the value to the prepared statement

$stmt->bindValue(':id', $id);

// Execute the prepared statement

$stmt->execute();

echo "Data deleted successfully!";

} catch (PDOException $e) {

echo "Delete operation failed: " . $e->getMessage();

die();

// Close the database connection

$pdo = null;

?>

<!-- HTML form for deleting data -->

<form method="POST" action="delete.php">

CSE-6001 Advanced Database Systems | United International University 33


PostgreSQL Tutorial

<input type="text" name="course_id" placeholder="ID of the record


to delete" required>

<button type="submit">Delete</button>

</form>

CSE-6001 Advanced Database Systems | United International University 34

You might also like