P
P
Pavel Bubentsov2017-07-18 06:58:21
PHP
Pavel Bubentsov, 2017-07-18 06:58:21

How to setup PHP+postgresql bundle?

Hello, the situation is such a project works using MySQL, according to the instructions of the management, it is necessary to migrate to POSTGRESQL.
Today there is a database, for example, on the host 192.168.1.3 port 3306 database name basa username admin password 123
in this case I have a database connection file bd.php:

<?php
session_start();
mysql_connect ("192.168.1.3:3306", "admin", "123");
mysql_select_db ("basa");
mysql_query("SET NAMES utf8");
?>

Data operations 1.php:
<? php
include_once("bd.php"); // подключение к базе данных
$resultat = mysql_query("SELECT * FROM table1");
$array= mysql_fetch_array($resultat); // Получение данных из таблицы table1
$query = "INSERT INTO table2 (name, nik )
 VALUES ('pavel', 'user')";
                    $result = mysql_query($query) or die(mysql_error()); // запись данных в таблицу table2 
?>

I don’t want to completely rewrite the code and change the structure, how to do the same thing on postgres (let the database be called basa2 port 5432, the rest of the data is the same).
PS: yesterday I heard for the first time that such a database exists...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kuznetsov, 2017-07-18
@DarkRaven

I would recommend you to look towards PDO. Yet a unified API for connecting and interacting with databases.
Make sure that your postgres extensions are enabled in php.ini.
The connection itself is quite simple, as is the subsequent work:

$userId = 20;
try {
    $db = new PDO("pgsql:dbname=basa;host=localhost", "admin", "123" );
    $sql = "SELECT * FROM public.users WHERE id = ?";
    $sqlQuery = $db->prepare($sql);
    $sqlQuery->execute([$userId]);
    
    while($result = $sqlQuery->fetch(PDO_FETCH_ASSOC)) 
    {
        echo "{$result['id']} / {$result['name']}<br />";      
    }

    $dbh = null;
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question