This question already has answers here:
Fatal error: Call to undefined function pg_connect()
(17 answers)
Closed 6 years ago.
So, basically what I am doing is a small system that allows students to take online tests and teachers can post an exam and let them know when they have it
It was all good while we worked in localhost, but then one of our requests was to use PostgreSQL instead for the database, which seemed cool to us
But now we are havving this issue while logging in
Database is already filled with the users and passwords, but it no longer allows us to acces the system no matter if we put a correct password/username set, or actually create a new account
This is the Connection.php file
<
?php
class Connection {
private static $instance;
private $connection;
private function __construct()
{
$cadena = "host='localhost' port='5432' dbname='newdb' user = 'postgres' password = 'system'";
$this->connection = pg_connect($cadena) or die ('Error');
$this->query("SET TIME ZONE -4");
}
public static function getInstance(){
if (!isset(self::$instance))
self::$instance = new Connection();
return self::$instance;
}
public function query($aQuery){
//echo "$aQuery<br>";
return pg_query($this->connection, $aQuery);
}
}
?>
Error always comes up on line 10 ($this->connection = pg_connect($cadena))
Saying that the pg:connect function is undefined, and given we are not experienced with the use of PG, I was hoping you could help us
Sorry if my english fails, as it is not my first language after all
Try to use below line to make connection string:
$cadena = "host=localhost port=5432 dbname=newdb user=postgres password=system";
Related
This question already has answers here:
MYSQLi error: User already has more than 'max_user_connections' active connections [duplicate]
(6 answers)
Closed 3 years ago.
public function getActiveUsers(){
$result = $this->con->query("SELECT * FROM `USERS` where `IsActive`=1");
$users = array();
while ($item = $result->fetch_assoc()) {
$users[] = $item;
}
return $users;
}//End Function
This is my PHP Function I am using to get active users from my DB (of my dashboard). Most of the other functions are written like this. They are written in a single PHP file (db-function.php). But first I defined the connection in a file called DB-Connet.php.
public function connect()
{
require_once 'source/config/config.php';
$this->con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
return $this->con;
}
And then created the connection in the construct of DbConnet class in db-function.php.
function __construct()
{
require_once 'DB-Connet.php';
$db = new DbConnect();
$this->con = $db->connect();
}
But when I try to visit the dashboard url It Displays a msg like this,
User adimn_user already has more than 'max_user_connections' active connections in ..../db-function.php on line 16.
What am I doing wrong? (My English is Bad. I am sorry. Edits are Wellcome. Thank you all.)
P.S : Is it okay if I close the connection in _destruct function of db-connect.php like this?
function __destruct() {
$this->con->close();
}
Always close the mysql connection if you do not need it. It saves memory and free up connection for next possible requests that might hit the Database.
I have been working on getting a PDO connection to establish within a class for the better half of a day. My problem is that as soon as I try to hit the new PDO(...) I get nothing, no errors nothing. Whatever I have after that will never run but my console will still be operational waiting for input. I have tried connecting in a few places including the "Driver" file where again, it doesn't do anything after I run the new PDO(...) instantiation. Here is part of my Database Class:
namespace App\Database;
class MySQL
{
private $Host;
private $DBName;
private $DBTable;
private $DBUser;
private $DBPassword;
private $DBPort;
private $PDO;
private $parameters;
private $bConnected = false;
public $querycount = 0;
function __construct($DBName, $DBTable)
{
$this->Host = getenv("DATABASE_HOST");
$this->DBPort = getenv("DATABASE_PORT");
$this->DBUser = getenv("DATABASE_USER");
$this->DBPassword = getenv("DATABASE_PASSWORD");
$this->DBName = $DBName;
$this->DBTable = $DBTable;
$this->Connect();
$this->$parameters = array();
}
private function Connect()
{
try{
echo "I am the good child and always print".PHP_EOL;
$this->PDO = new PDO("mysql:host=localhost;port=33061;dbname=store", "root", "password");
echo "Please Print Me <3".PHP_EOL;
$this->bConnected = true;
} catch (PDOException $e){
echo $e->getMessage();
die();
}
}
I have checked values for Host, DBPort etc and in this code below I have all their values hard coded so nothing should be wrong due to the formatting of insert the variables in their proper slots. I know PDO is turned on because I can use it in other projects but my catch isn't catching anything, I can get the first echo to run but the second one never appears. Any help would be awesome because at this point I am scratching my head at why I can't get this to connect.
Thanks!
If I am unclear I can try and provide clarity and I can also show the driver file if need be but basically, it is just calling the constructor just fine and the connect function is giving us problems.
I have been going over each line of my code for about the last hour or so if not more. I found some discrepancies in my variables. I used in a couple places $this->$parameters
or other variations which didn't seem to cause an error for some reason but rendered the code inoperable. I'm not sure why it wasn't throwing an error about the variables but it would seem that is what caused my issue.
Thank you for your time and help!
This question already has answers here:
How do I parse object data from MySQL database using PHP PDO?
(1 answer)
PHP/PDO - use variable assignment as fetch-statement
(4 answers)
Closed 5 years ago.
After 10 years away from PHP coding, am getting back in the swing of things going through tutorials. I discovered things have changed, and PDO is the new standard to connect to MySQL.
I set up small projects. I am trying to build my own Class database, and things get all sideways, and I don't figure out why.
So here is my database class:
<?PHP
$Db = new database;
class database
{
/////////////
//Attributs//
/////////////
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $bdd;
/////////////////////
// internal process//
/////////////////////
private function activateDB()
{
$this->checkList();
$this->dbInitilisation();
$this->dbConnection();
}
////////////////////////
//Check Websiteconfig//
////////////////////////
private function checkList()
{
if(!file_exists('website-config.ini')){
die('missing configuration file.');
}
}
///////////
//Db init//
///////////
private function dbInitilisation()
{
// Load config file for database connection info
$config = parse_ini_file("website-config.ini");
$this->db_host=$config['db_host'];
$this->db_user=$config['db_login'];
$this->db_pass=$config['db_password'];
$this->db_name=$config['db_name'];
}
/////////////////
//Db connection//
/////////////////
private function dbConnection()
{
try
{
$this->bdd = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name.';charset=utf8', 'root', '');
$this->bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $e)
{
die('error '.$e);
}
}
public function dbQuery($user_query, $parameters)
{
$this->activateDB();
$query = $this->bdd->prepare($user_query);
$query->execute($parameters);
$query->fetch();
return $query;
}
}
?>
and, here is how I am calling it:
$values[':user_id']='1';
$result=($Db->dbQuery('SELECT user_username FROM user WHERE user_id = :user_id',$values));
print_r($result);
When I was not using pdo, and writing my function like normal, I had what I wanted. Now, not any more.
Does anyone has a clue on what I am doing wrong? Do you have any kind of comment on how to improve my overall stuff?
PS: I did read around before coming here (like here: http://php.net/manual/fr/pdostatement.fetch.php (I thought my issue were maybe with the type of fetch, but again, when not in OOP, my code runs ok as it is.) Or here PHP: Database Connection Class Constructor Method but the solution give here is to go on someone else code library, and not allowing to understand what I am actually doing wrong.
I am not very experienced in php oop. Moreover, when mysqli comes with php oop, it make me more confused about using it in best efficient way. Anyway, first look at my connection class:
<?php
//connectionclass.php
class connection{
public $conn;
public $warn;
public $err;
function __construct(){
$this->connect();
}
private function connect(){
$this->conn = # new mysqli('localhost', 'sever_user', 'user_password');
if ($this->conn->connect_error) {
$this->conn = FALSE;
$this->warn = '<br />Failed to connect database! Please try again later';
}
}
public function get_data($qry){
$result = $this->conn->query($qry);
if($result->num_rows>=1){
return $result;
}else{
$this->err = $this->conn->error;
return FALSE;
}
$result->free();
}
public function post_data($qry){
$this->conn->query($qry);
if($this->conn->affected_rows>=1){
return TRUE;
}else{
$this->err = $this->conn->error;
return FALSE;
}
}
}
?>
Now please structure of a php page which uses mysql database to store and get data:
<?php
//login.php
include('/include/connectionclass.php');
$db = new connection();
$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
if($data){
while($row=$data->fetch_assoc()){
echo 'User Name: ':.$row["user_name"].' Age: '.$row["age"];
}
}
?>
So my login.php uses connection class to get data about users. All the things are running well. But one things made me confused. In connectionclass.php $this->conn is itself an object as it calls new mysqli. So this is an object inside another object $db. Moreover, When I am using $data = $db->get_data($query);, a result set is created inside object $db by method get_data, then this result set is copied into a variable $data inside login.php page.
So according to me, actually two result sets/data sets are creating here, one inside db object and one inside login page. Is it right way to use mysqli and php to get dataset from mysql database? Will it use more memory and server resources when the dataset is larger (when have to get large amount of data for many users)?
If it is not right way, please explain your points and please give me code which can be used efficiently for php oop and mysqli.
This question already has answers here:
Synchronized functions in PHP
(6 answers)
Closed 9 years ago.
I've got a php application that requires to make a connection to a server which authenticates with a token, this token stays valid until connection is lost.
When another connection is made while the first is still open my application crashes because the token is different from the currently connected one...
public function connect()
{
$Socket = fsockopen("192.168.1.1", 1234);
if ($Socket !== false) {
stream_set_timeout($Socket, static::TIMEOUT_SEC, static::TIMEOUT_USEC);
$this->socket = $Socket;
$this->sendeverything;
}
}
How am I able to run a function like:
function gogogo() {
connect();
}
multiple times without having them running simultaneously
Sorry for my bad english
Most easy solution would be to have a is_connected function:
function connect() {
if(is_already_connected()) {
return;
}
// ... your connect logic
}
In the is_already_connected() you'll have to write some intelligent code to determine if there is an open connection.
You can also create a kind of singleton connection (although this suggestion would probably instantiate a lot of debate about the use of singletons ;))
Try something like this...
<?php
class Connection {
public $Socket = null;
public function connect(){
// Checking if Socket already has a pointer :P
if((bool)$this->Socket){
return true;
}
$this->Socket = fsockopen("192.168.1.1", 1234);
if ($this->Socket !== false) {
stream_set_timeout($this->Socket, static::TIMEOUT_SEC, static::TIMEOUT_USEC);
$this->sendeverything();
}
}
}
$myconnect = new Connection();
$myconnect->connect();
$myconnect->connect();
?>
As mentioned in this question you can use sem_aquire for this. Something like:
function connect(){
$key = "192.168.1.1:1234" ;
try{
$sem = sem_get( $SEMKey);
sem_acquire($sem);
//Do connecty stuff here
sem_release($sem);
}catch(Exception $ex){
//Exception handling
}finally{
//Finally only available in PHP 5.5 place this in catch and try if < 5.5
sem_release($sem);
}
}
Note that this is entirely untested and wont work on windows. If you are on windows you can use flock - again as mentioned in the above question.