How to connect to the database with postgresql using php?

3
$dbservername = "localhost";
$dbusername = "postgres";

$dbname = "asistencia";
$dbpassword = "123456";

$puerto = "5432";


$con=pg_connect("host=localhost, dbname=asistencia, user=postgres, $dbname, $dbpassword");

I have previously connected to a database using xampp and mysql, but this time it is especially problematic, I tried to approach the connection in several ways and I can not make the connection, with the connection above I only got:

  

Warning: pg_connect() : Unable to connect to PostgreSQL server: missing   "=" after "assistance," in connection info string in    /var/www/html/libreta/conexion.php on line 14

Why is it missing a = after assistance? I do not see the meaning, try placing the port after assistance, but I get the same error.

  • Does the order in which I place the data within the parentheses of pg_connect() matter?
  • I see that now a port is needed to make the connection, how do I make sure exactly what data do I need and what are the data of the machine where I am working?

Many doubts, I keep investigating, but I just can not make it work. I'm using pgAdmin III .

    
asked by Hoozuki 27.07.2018 в 16:08
source

3 answers

2

Your code should be a little cleaner and if you declare the variables above you are not using them below, you could do something like this:

$dbservername = "localhost";
$dbusername = "postgres";
$dbname = "asistencia";
$dbpassword = "123456";
$puerto = "5432";
$con=pg_connect("host=$dbservername port=$puerto dbname=$dbname user=$dbusername password=$dbpassword");
    
answered by 27.07.2018 / 16:23
source
2
$host="192.168.0.1";
$port="5432";
$user="postgres";
$pass="clave";
$dbname="db";

$connect = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$pass") or die('No se ha podido conectar: ' . pg_last_error());

I think you need the port to pass it in the function

    
answered by 27.07.2018 в 16:18
2

I commented that another way to connect is through the driver PDO ; as follows

<?php 
$host="192.168.0.1";
$port="5432";
$user="postgres";
$pass="clave";
$dbname="db";

$dbh = new PDO("pgsql:dbname=$dbname;host=$host;port=$port", $user, $dbpass); 
?>

Where, as you can see at the beginning, we indicate which manager should point to when we write pgsql

In the same way we can pass the connection port

Here you have more references from part of the official PHP documentation

link

    
answered by 27.07.2018 в 16:23