Postgresql php connection string

Connecting to PostgreSQL

Summary: in this tutorial, you will learn how to connect to a PostgreSQL database server using PHP PDO.

Prerequisites

To make a connection to the PostgreSQL database server using PHP PDO, you need to have:

  • A PostgreSQL database server, a database, and an account with a username and password that can access the database.
  • PHP PDO PostgreSQL driver enabled in the php.ini file.

1) PostgreSQL database parameters

Suppose you have the following PostgreSQL database parameters:

  • A PostgreSQL database server on the localhost .
  • The dvdrental sample database.
  • The account with the user postgres and password postgres that can access the dvdrental database on the local database server

The following creates a new database configuration file named config.php that stores the PostgreSQL database parameters:

 $host= 'localhost'; $db = 'dvdrental'; $user = 'postgres'; $password = 'postgres'; // change to your passwordCode language: HTML, XML (xml)

To use these parameters, you include the config.php file in the script that connects to the PostgreSQL using the require construct.

2) Enable PostgreSQL driver

The PDO_PGSQL is a driver that implements the PDO interface. It allows you to access PostgreSQL databases from PHP.

To check if the PDO_PGSQL driver is enabled, you open the php.ini file. Typically, the php.ini file is located under the php directory. For example, if you use XAMPP on Windows, you can find the php.ini file under the C:\xampp\php directory.

in the php.ini file, you can find the following line:

;extension=php_pdo_pgsql.dll

If you see the comma( ; ) placed at the beginning of the line, it means that the line is commented and the database driver is not enabled.

To enable the driver, you need to uncomment the line by removing the comma ( ; ) like this:

extension=php_pdo_pgsql.dll

After that, you need to restart the web server to apply the change.

PostgreSQL data source name

The data source name or DSN holds database parameters that enable access to a database system. The data source name of the PostgreSQL consists of the following parameters:

  • pgsql: is the DNS prefix.
  • host: the host of the server where the PostgreSQL runs.
  • port: the port to which PostgreSQL listens. The default PostgreSQL’s port is 5432 .
  • dbname: the database name that you want to connect to.
  • And other parameters.

The following shows a DSN that connects to dvdrental database in the local PostgreSQL Server, port 5432:

pgsql:host=localhost;port=5432;dbname=dvdrental;

Connecting to PostgreSQL

The following illustrates how to connect to the dvdrental database in PostgreSQL database server:

 require_once 'config.php'; try < $dsn = "pgsql:host=$host;port=5432;dbname=$db;"; // make a database connection $pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); if ($pdo) < echo "Connected to the $db database successfully!"; > > catch (PDOException $e) < die($e->getMessage()); > finally < if ($pdo) < $pdo = null; > > Code language: HTML, XML (xml)
  • First, make a new connection to the PostgreSQL database by creating a new instance of the PDO class.
  • Second, show a message if the database connection is established successfully; otherwise, show an error message.

The following option instruct PDO to set an error code and throw an exception if an error occurs:

[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]Code language: PHP (php)

PDO has three exception handling options:

  • PDO::ERROR_SILENT – PDO sets an error code for inspecting using the PDO::errorCode() and PDO::errorInfo() methods. The PDO::ERROR_SILENT is the default mode.
  • PDO::ERRMODE_WARNING – Besides setting the error code, PDO will issue an E_WARNING message.
  • PDO::ERRMODE_EXCEPTION – Besides setting the error code, PDO will raise a PDOException .

Note that PHP automatically closes the database connection when the script ends. If you want to close the database connection explicitly, you can set the PDO instance to null:

 $pdo = null;Code language: HTML, XML (xml)

The following connect.php script defines a connect() function that makes a connection to the PostgreSQL database and returns an instance of the PDO class:

 require_once 'config.php'; function connect(string $host, string $db, string $user, string $password): PDO < try < $dsn = "pgsql:host=$host;port=5432;dbname=$db;"; // make a database connection return new PDO( $dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] ); > catch (PDOException $e) < die($e->getMessage()); > > return connect($host, $db, $user, $password);Code language: HTML, XML (xml)

To use this connect.php in a script, you use the require construct as follows:

 $pdo = require 'connect.php'; // start working with the databaseCode language: HTML, XML (xml)

Summary

  • Enable PostgreSQL extension in php.ini file by removing the semicolon ( ; ) from the line extension=php_pdo_pgsql.dll
  • Create a new instance of PDO by passing the data source name (DSN) to its constructor to make a connection to the PostgreSQL database server.

Источник

pg_connect

pg_connect() открывает соединение с базой данных PostgreSQL, определенное строкой connection_string .

При повторном вызове функции pg_connect() с теми же значениями параметров в connection_string функция вернет существующее подключение. Чтобы принудительно создать новое соединение, необходимо передать строку подключения функции PGSQL_CONNECT_FORCE_NEW в качестве параметра connect_type .

Прежний синтаксис с множеством параметров $conn = pg_connect(«host», «port», «options», «tty», «dbname») считается устаревшим.

Список параметров

Строка connection_string может быть пустой строкой, или содержать несколько параметров разделенных пробелами. Каждый параметр указывается как keyword = value. Пробелы вокруг знака равно необязательны. Пустые строки в качестве значения или значения, содержащие пробелы отделяются одинарными кавычками, как например, keyword = ‘a value’. Для задания одинарных кавычек и обратных слешей в качестве значений их необходимо экранировать обратным слешем, то есть \’ и \\.

Список основных ключевых слов: host , hostaddr , port , dbname (значение по умолчанию для параметра user ), user , password , connect_timeout , options , tty (игнорируется), sslmode , requiressl (устарело в связи с использованием параметра sslmode ), и service . Какие из этих аргументов будут обработаны, зависит от версии PostgreSQL.

Параметр options служит для установки параметров командной строки, которые обработаны сервером.

Если в функцию передана константа PGSQL_CONNECT_FORCE_NEW , будет создаваться новое подключение, даже если connection_string идентична строке существующего подключения.

Если передана константа PGSQL_CONNECT_ASYNC , то соединение устанавливается асинхронным. Состояние соединения можно проверить с помощью функций pg_connect_poll() или pg_connection_status() .

Возвращаемые значения

Ресурс соединения с базой данных PostgreSQL либо FALSE , если подключиться не удалось.

Список изменений

Версия Описание
5.6.0 Добавлена поддержка константы PGSQL_CONNECT_ASYNC для параметра connect_type .

Примеры

Пример #1 Использование функции pg_connect()

$dbconn = pg_connect ( «dbname=mary» );
//подключиться к базе «mary»

$dbconn2 = pg_connect ( «host=localhost port=5432 dbname=mary» );
//подключиться к базе «mary» на хосте «localhost», порт «5432»

$dbconn3 = pg_connect ( «host=sheep port=5432 dbname=mary user=lamb password=foo» );
//подключиться к базе «mary» на хосте «sheep», используя имя пользователя и пароль

$conn_string = «host=sheep port=5432 dbname=test user=lamb password=bar» ;
$dbconn4 = pg_connect ( $conn_string );
//подключиться к базе «test» на хосте «sheep», используя имя пользователя и пароль

$dbconn5 = pg_connect ( «host=localhost options=’—client_encoding=UTF8′» );
//подключиться к базе на хосте «localhost» и передать параметр командной строки, задающий кодировку UTF-8
?>

Смотрите также

  • pg_pconnect() — Открывает постоянное соединение с сервером PostgreSQL
  • pg_close() — Закрывает соединение с базой данных PostgreSQL
  • pg_host() — Возвращает имя хоста, соответствующего подключению
  • pg_port() — Возвращает номер порта, соответствующий заданному соединению
  • pg_tty() — Возвращает имя терминала TTY, связанное с соединением
  • pg_options() — Получение параметров соединения с сервером баз данных
  • pg_dbname() — Определяет имя базы данных

Источник

pg_connect

pg_connect () открывает соединение с базой данных PostgreSQL, указанной в connection_string .

Если второй вызов на pg_connect () с тем же connection_string как существующее соединение, существующее соединение будет возвращено , если вы не пройдете PGSQL_CONNECT_FORCE_NEW в качестве flags .

Старый синтаксис с несколькими параметрами $ conn = pg_connect («host», «port», «options», «tty», «dbname») устарел.

Parameters

connection_string может быть пустым , чтобы использовать все параметры по умолчанию, или он может содержать один или несколько параметров параметров , разделенных пробелами. Настройка каждого параметра имеет вид keyword = value . Пробелы вокруг знака равенства необязательны. Чтобы записать пустое значение или значение, содержащее пробелы, заключите его в одинарные кавычки, например, keyword = ‘a value’ . Одиночные кавычки и обратные косые черты внутри значения должны быть экранированы обратной косой чертой, т. Е. \ ‘И \\.

В настоящее время распознаются ключевые слова параметров: host , hostaddr , port , dbname (по умолчанию значение user ), user , password , connect_timeout , options , tty (игнорируется), sslmode , requiressl (устарело в пользу sslmode ) и service . Какие из этих аргументов существуют, зависит от вашей версии PostgreSQL.

Параметр options может использоваться для установки параметров командной строки, которые будут вызываться сервером.

Если PGSQL_CONNECT_FORCE_NEW передается, то создается новое соединение, даже если connection_string идентично существующему соединению.

Если PGSQL_CONNECT_ASYNC , то соединение устанавливается асинхронно. Затем состояние соединения можно проверить с помощью pg_connect_poll () или pg_connection_status () .

Return Values

Возвращает экземпляр PgSql \ Connection в случае успеха или false в случае ошибки.

Источник

How to use PostgreSQL

PHP supports PostgreSQL, the pg_connect() function is used to connect to a PostgreSQL database server. Once a connection has been established, SQL commands can be executed with the pg_query() function.

Connecting to PostgreSQL

Then, pg_connect() connects to the data source. You have to provide a connection string that contains all important data, including the host, port, name of the database, and user credentials.

 echo 'Connected to the database.'; pg_close($conn);

Sending SQL with pg_query()

The function pg_query() sends SQL to the PostgreSQL installation.

Sending SQL to PostgreSQL

pg_escape_string()

Escaping potentially dangerous characters such as single quotes is a must; this can be done with the pg_escape_string() function. In this code, you see the following code accepts an HTML form and writes it to the database.

Inserting Data in PostgreSQL

Another way to insert or update data in PostgreSQL comes in the form of the functions pg_insert() and pg_update() .

The first parameter must be the database handle, the second parameter is the table to be inserted into/updated, and the third parameter contains some data in the form of an associative array (column names are the keys).

Inserting Data with pg_insert to PostgreSQL

$name, 'email'=>$email); pg_insert($conn, 'user_table', $data); echo 'Record saved.'; pg_close($conn);

Alternatively, you can use pg_query function with INSERT SQL statement to insert new records:

Updating Data in PostgreSQL

In the event of an UPDATE SQL statement, the update condition must also be submitted as an array in the fourth parameter of the function.

Updating Data with pg_update to PostgreSQL

$name, 'email'=>$email); $condition = array(); $condition['id'] = 21; pg_update($conn, 'user_table', $data, $condition); echo 'Record updated.'; pg_close($conn);

Alternatively, you can use the UPDATE statement in the pg_query function :

Updating record with pg_query()

Retrieving Results of a Query to PostgreSQL

The return value of a call to pg_query() is a pointer to a resultset that can be used with these functions:

  • pg_fetch_assoc() returns the current row in the resultset as an associative array
  • pg_fetch_object() returns the current row in the resultset as an object
  • pg_fetch_row() returns the current row in the resultset as a numeric array
  • pg_fetch_all() returns the complete resultset as an array of associative arrays

Retrieving Data from PostgreSQL

The code uses pg_fetch_row() to read out all data from the user_table table.

Alternatively, pg_select() works similarly to pg_insert() and pg_update() . Just provide a database handle, a table name, and maybe a WHERE clause in the form of an array, and you get the complete resultset as an array of (associative) arrays.

The preceding code can be written with pg_query and SQL SELECT statement, see the following code:

Working with Databases:

Источник

Читайте также:  Css for chrome browser
Оцените статью