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.
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.
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";
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 an answer here:
PHP: mysql_connect not returning FALSE
(1 answer)
Closed 8 years ago.
I'm very new to OOP and am trying to learn it. So please excuse my noobness. I'm trying to connect to mysql and to test whether the connection is successful or not, I'm using if-else conditions.
Surprisingly, the mysql_connect is always returning true even on passing wrong login credentials. Now I'm trying to figure out why it does and after spending about 20 minutes, I gave up. Hence, I came here to seek the help of the community. Here is my code:
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if(! $dbhandle)
{
die('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
$test = new test();
Please don't use the mysql_* functions, there are many, many reasons why - which are well documented online. They are also deprecated and due to be removed.
You'd be much better off using PDO!
Also I'd strongly advise abstracting this database code into a dedicated database class, which can be injected where necessary.
On-topic:
That code snippet seems to work for me, have you tried var_dumping $conn? Does that user have correct rights?
I also hope that you don't have a production server which allows root login without a password!
Ignoring the fact that you're using mysql_* functions rather than mysqli or pdo functions, you should utilise exceptions in OOP code rather than die(). Other than that, I can't replicate your problem - it may be that your mysql server is set up to accept passwordless logins.
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
// returns false on failure
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
throw new RuntimeException('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if (!$dbhandle)
{
throw new RuntimeException('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
try {
$test = new test();
} catch (RuntimeException $ex) {
die($ex->getMessage());
}
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.