Reputation: 157
I want to create a function that connects to my psql DB "function connectDB(){ }" using pg_pconnect() , and i have multiple functions that do select/ update queries, I am sending the connection as parameter =in these functions to decrease creating multiple connections:
function connectDB() {
$conStr = "host=" . DB_HOST . " dbname=" . DB_NAME . " user=" . DB_USER . " password=" . DB_PASS;
$connection = pg_pconnect($conStr);
return $connection;
}
function selectDB($connection) {
$ids = '2,34,56,5,555';
.
.
.
....
$query = "SELECT from users where id IN ($ids)";
$result = pg_query($connection, $query);
}
am getting this error: invalid connection resource id#14 I think the connection is closed before the query is executed
Upvotes: 0
Views: 238
Reputation: 1770
Perhaps you should consider how to make a data access layer in your code. Something like this
class dal{
private $connection;
function connectDB() {
$conStr = "host=" . DB_HOST . " dbname=" . DB_NAME . " user=" . DB_USER . " password=" . DB_PASS;
$this->connection = pg_pconnect($conStr);
}
function selectDB($ids) {
.
.
.
....
$query = "SELECT from users where id IN ($ids)";
$result = pg_query($this->connection, $query);
return $result;
}
}
now use an instance of this dalin your code. Use the industry standards to make your life easier.
Upvotes: 1