How can I check if a db-connection is open in PHP?
How can I get a reference to this connection?
How can I determine if it is MySQL, Postgres or something else?
Ideally you would know the variable the connection is saved into. Without this it becomes a hassle to find it. It means you would have to loop through every variable and test each one, but doing this for any reason can be a pain because it wont find variables outside of the current scope. You can loop the current variables using:
foreach(get_defined_vars() as $x){
// Code
}
To check if a variable is a valid connection you can use the below code, it should return an integer:
if(mysql_thread_id($connection){
// Connection exists
}
Once you know its a connection you can use the following to return the type of connection, eg, mysql.
echo get_resource_type($connection);
You'd have to iterate over every defined variable and figure out if it's a resource handle or not. Try get_defined_vars().
Probably the best solution to the problem is to not lose track of the DB connection in the first place.
Consider integrating an ORM into your project such as Doctrine or Propel, or if you want something a little more lightweight, consider a DBAL such as Zend_Db. All of these solutions encapsulate the database connections in class instances, ensuring that they are always available to your code if necessary.
In general terms, I don't think it's really possible, not at least with some sort of complicate workaround. You can, for instance, loop through all defined variables:
foreach(get_defined_vars() as $variable){
if( is_resource($variable) && get_resource_type($variable)=='mysql link' ){
// Found a connection!
var_dump($variable);
}
}
Though, in fact, a connection remains available even if assigned to a local variable out of current scope:
function foo(){
$conn = mysql_connect('localhost', 'test', 'test');
}
foo();
$res = mysql_query('SELECT NOW() AS what_is_the_time');
if( $row = mysql_fetch_assoc($res) ){
var_dump($row);
}
The problem is that PHP doesn't really care about variables when talking about connections:
// One connection and zero variables!
mysql_connect('localhost', 'test', 'test');
$res = mysql_query('SELECT NOW() AS what_is_the_time');
if( $row = mysql_fetch_assoc($res) ){
var_dump($row);
}
You can try and find information about current connection:
var_dump(mysql_thread_id());
// int(2696)
... though many of the functions will just attempt to stablish a new connection if there isn't one so must take care of warnings...:
Warning: mysql_thread_id(): Access denied for user ''#'localhost' (using password: NO)
bool(false)
... unless your configuration actually allows a succesful credential-less connnection attempt.
I'm pretty sure that, whatever you want to do, can be done in an entirely different way :)
Related
I'm kinda going crazy about this problem. I can't do it myself so I need the community to help me get this thing solved. I've been spending hours on this because I didn't know where to look. I now know a possible fix but it's just messy (read on). I just need someone who knows more about this than I do.
This is my situation:
I want to use 2 or more mysql connections.
I use OOP
I have a class called dbase, it has two functions, setConnection and getConnection and two class variables called $connection and $dbaseName.
In my main project file I include dbase and create two objects:
dbase
maindbase
then I do:
$this->dbase->setConnection($server, $uname, $pword);
$this->maindbase->setConnection($server, $uname, $pword);
the setConnection function looks like this:
function setConnection ($server, $serv_Username, $serv_Password) {
$this->connection = mysql_connect($server, $serv_Username, $serv_Password, true);
// echo $this->connection . "<BR>";
}
I echo it to see the resourcenumber and added true to mysql_connect (and I know it's deprecated since 5.5, I'm not here for that).
Now, as I understand OOP, the class variables are set per object. So $connection from dbase will never be the same as maindbase (unless, of course, I use the same credentials, but even then it will create a new link because of the $new_link option I enabled). They both have different resource ID's.
My problem:
In class dbase I also have a function which runs a query like this:
$connection = $this->getConnection();
$dbase_name = $this->getDbaseName();
mysql_select_db($dbase_name, $connection);
$q = "SELECT * FROM {$table_name} WHERE {$column} LIKE '{$value}'";
$result = mysql_query($q);
Now, when I use it like this, it will ALWAYS use the FIRST $connection that has been set in class dbase and it doesn't matter which object this is, either object dbase or maindbase.
I get this error:
Table 'testdbase1.skye_domains' doesn't exist
object dbase is connected to testdbase1
object maindbase is connected to testdbase2
the above error I get when trying to select results using the maindbase object.
When I remove the $connection string from mysql_select_db it works perfectly because it will try to open a new connection as if using mysql_connect.
Why is this? This is impossible right? How can objectmaindbase have the same $connection as object dbase? They are in NO WAY connected to eachother... Is PHP somehow using a global mysql_connect variable or buffer which I'm not aware about?
I would like to keep using connectionstrings as this is just handy now and then. Leaving the $connection string out seems messy.
Does anybody have any suggestions I can try to make PHP (or my head) sane again?
Try to put echo $this->connection EVERYWHERE you use it. Also, create an "id" member and fill it with a unique value upon constructing a dbase-object and echo it along the value of $this->connection. This way you can track where what happens to your connection.
And check if there's maybe some place outside of the class that assigns $foo->connection. If you're not using "private" on the members, you're bound to have such problems when you e.g. forget to remove a hack or an experiment from unrelated parts of your code.
I am used to mysql database access using the procedural mysql method. I am a beginner - intermediate programmer.
I am trying to learn the PDO api, however all resources which discuss using PDO show the connection string, username and password.
e.g.
<?php
try {
$db_conn = new PDO('mysql:host=localhost;dbname=databaseName','username', 'password');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$sql = 'SELECT * FROM Products';
$stmt = $db_conn->prepare($sql);
...
...
...
?>
What I want, and think would be better programming is to put my PDO connection into a new file. then where I want to run an SQL query, I require_once('PDO.php') or similar.
The problem I have with this is as follows:
How do I close the connection? Simply $db_conn = null; ??
Should I close the connection after each query is run, then re-open the connection?
Should I close the connection or is it automatically destroyed when the user closes the browser?
I am working from a book called PHP Master: Writing Cutting Edge Code. http://www.sitepoint.com/books/phppro1/ and this has completely omitted any reference to closing the connection / destroying the object after it has been used.
Furthermore, I have looked at online tutorials, and they all connect to the database using PDO inline as opposed to having a separate database connector. This I am not happy with for many reasons:
I have to type username & password to connect every time.
If I get a developer to take a look at code / write some code, they will all have access to the database.
If I change the DB username & Password, then each file which connects to the database will need to be updated.
Could anybody recommend a better resource? Could anybody advise on what is the best practice way to do this?
Many thanks
Your question about how to store the database name, username and password have nothing to do with the capabilities of PDO. This is an implementation choice. The way you use to work with procedural functions can also be applied to PDO, the difference is that with PDO you work with objects instead.
So for simplicity, store the PDO creation of an object, either in a function or class, in which you can create the PDO instance anytime, e.g.
function createPDO($cfg) {
try {
return new PDO("mysql:host=".$cfg['host'].",port:".($cfg['port']).";dbname=".($cfg['name']).";",$cfg['username'], $cfg['password']);
} catch(PDOException $e) {
// handle exceptions accordingly
}
}
You can centralise these in whatever PHP file you like to include, just like you were used with the procedural functions.
You have two choices, either put all the relevant database information inside the createPDO, or use something like a config ($cfg) variable to store all this information.
$config = array();
$config['db'] = array(
'host' => 'localhost',
'name' => 'databse',
'username' => 'userx',
'password' => 'passy'
/* .. etc */
)
Using the createPDO function would be as followed
$db_conn = createPDO($config['db']);
For connections closing, each connection made to the database automatically disconnects after PHP exits its execution. You can however, close the connection if you wish, by setting the variable of the PDO object you assigned it to, in this example (and in yours) $db_conn to null
$db_conn = null; // connection closed.
The PDO has a manual http://php.net/manual/en/book.pdo.php here, which is a good start getting to know PDO a bit better.
You do not close the connection after a query, you simply leave it open for the next query. When PHP exists and your page is shown, the connection will be closed automatic.
It is a good idea to put the db stuff in a separate file and include that.
Even better, put all your db stuff in a class in use that.
Have a look at the pdo php page. Although not the best examples, they should get you started.
My question is I am using the variable $db in my general script code and within one of my functions. It's purpose is to be the variable that is used for MySQL connections. I have a need inside a function to write some data to the database. In my script I cannot assume that an existing db connection will be open so I open a new one and close it before the function exits. Ever since doing this I am getting an error after the script runs saying the MySQL reference is bad / doesn't exist.
The only thing I can pin it to is in my core code I use the variable $db as the variable name for database connection. I also use the same variable in the function. I did not imagine this would be a problem because I do not use global in front of $db in the function. This should mean the $db I reference in my function is in the functions private scope but it seems to be closing the public $db's connection.
Any thoughts?
Fragments of my code are:
database.php
db_connect()
{
// open mysql db connection and return it;
}
db_close( &$db )
{
// close the passed by reference db connection
}
api.php
api_verify( $keyid, $userid, $key )
{
// open a new db connection
$db = db_connect();
// check for errors. if any errors are found note them in the db
// close the db
db_close($db);
}
main.php
include api.php;
include database.php;
// open a connection to the db
$db = db_connect();
// pull a list of things to process from the db and move through them one at a time
// call api_verify() on each key before working through it's data.
db_close($db)
To manage DB connections, you can create a class rather than a pair of functions. If where you say "MySQL reference", the exact error refers to a "MySQL resource", then you are using the outdated mysql extension and should switch to a more modern extension, such as PDO.
class DBConnection {
protected static $_connections = array(),
static connect($dsn) {
if (!isset(self::$_connections[$dsn])) {
$credentials = self::getCredentials();
/* Create connection. For example: */
try {
self::$_connections[$dsn][0] = new PDO($dsn, $credentials['username'], $credentials['password']);
} catch (PDOException $exc) {
// erase the frame w/ password from call trace to prevent leak.
throw new PDOException($exc->getMessage(), $exc->getCode());
}
/* End create connection example */
self::$_connections[$dsn][0]->dsn = $dsn;
}
++self::$_connections[$dsn]['count'];
return self::$_connections[$dsn][0];
}
static close($db) {
if (isset(self::$_connections[$db->dsn])) {
if (--(self::$_connections[$db->dsn]['count']) < 1) {
unset(self::$_connections[$db->dsn]);
}
}
}
static getCredentials() {
/* credentials can be stored in configuration file or script, in this method, or some other approach of your own devising */
}
}
Note that this isn't exactly OOP (it is, but only in a technical sense). The above doesn't lend itself well to unit testing. If you want a more OO approach (which will be more amenable to unit testing), extend or wrap PDO. Using dependency injection can also help with the coupling issues of the above.
I assume you are opening a connection to the same database with the same username/password at each of the places you call db_connect. When doing so,unless your db_connect explicitly specifies, that you are creating a new link, it will return an already opened link.If that link is then closed using db_close(), it will also close the other connection, since the link is the same. If you are using mysql_connect to connect to the database, it takes an argument called new link
new_link
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.
Refer to http://php.net/manual/en/function.mysql-connect.php
I'm not sure if this is the issue you are facing. Hope it helps.
I would assume what is happening is the connect cancels out because there already is a connection, and then the close ends the current connection.
I would recommend either A) start a connection at the beginning of the file, and just know it's always there (what I do); or B) check the to see if the $db variable is set, if not then create the connection, and always end the connection at the end of the file.
HI everyone, I was just wondering what the best way to make multiple queries against tables in a mysql databases is. Should I be making a new mysqli object for every different .php page ($mysqli = new mysqli("localhost", "root", "root", "db");)?
Or is there a way to reuse this one time over all php files in my website? Any suggestions would be pretty cool
My vote would be to take an OOP approach. I would have one script that has a DB conn class in it and a method in that class to check if a connection exists and if it does returns the connection object. You could have that db class script referenced [ include_once(); ] on the pages that need to access the database. Then it would be a matter of instantiating the db object, firing the "if-exists" method and if it returns true then just utilize the existing connection within the object.
You could also take a look at utilizing persitent connections to the DB
Persistent connections
However honestly you will be better off in the long run and scalability of your application to handle the db connection management yourself rather then leaving a connection constantly open.
Here is an example of how I would structure that class:
As a note, made by #alex, the mysql_error() should not be echoed to the page in an environment where the display_errors() is set to display all warnings. (e.g error_reporting(E_WARNING);)
class dbconn {
protected $database;
function __construct(){
$this->connect();
}
protected function connect() {
$this->database = mysql_connect('host', 'user', 'pass') or die("<p>Error connecting to the database<br /><strong>" . mysql_error() ."</strong></p>" );
mysql_select_db('databasename') or die("<p>Error selecting the database<br />" . mysql_error() . "</strong></p>");
}
function __destruct(){
mysql_close($this->database);
}
function db(){
if (!isset($this->database)) {
$this->connect();
}
return $this->database;
}
}
You need to create the connection for each page, as each PHP script's lifetime is that of the request.
However, you can place the connection code in one file and then include it from all pages.
You could create a connect.php that validates it's being included by your application, and then creates a DB connection.
You could then include that file at the beginning of your application's init, or the beginning of any independent script that needs a connection =)
Depends on structure of website. If you have:
<a herf='login.php'>login</a>
<a herf='register.php'>register</a>
<a herf='about.php'>about</a>
..., then you'll have to connect in every PHP file, i.e., in login.php, in register.php and in about.php. To make it easier, I would either create config.php file which holds user/pass, or even do like Shad said.
You might also have index.php that contains something like this:
if ( !isset($_GET['module']) ) {
$_GET['module'] = 'about';
}
switch ( $_GET['module'] ) {
default:
case 'about':
include 'about.php';
break;
case 'login':
include 'login.php';
break;
case 'register':
include 'register.php';
break;
}
And HTML code:
<a herf='?module=login'>login</a>
<a herf='?module=register'>register</a>
<a herf='?module=about'>about</a>
In this case you can connect in index.php and then pass the connection to all other involved files.
The 2nd way seems to be more common to me, i.e., it feels more intuitive, more handy and that's what I always do.
I believe that in some cases it might be worthy (performance-wise) to use persistent connections and reserve/release connection when needed (either for transaction or even for single query). For example, simple system that I'm now working with takes 70ms-100ms to generate, and it takes only 40ms-50ms to do SQL queries. If using "single connection" approach, it means that connection is wasted for about 50% of time, while "reserve/release connection when needed" with persistent connections would not have such issue.
One more thing - I would advise you to create some wrapper, i.e., some DBConnection class that connects to DB in constructor and has methods like select() (returns array of data), selectValue() (returns single value, e.g., $db->selectValue('select count(*) from user') would return (int)$numberOfUsers), some exec() for inserts and updates etc.
Is there a way to set the default database handle with mysql_query? So I know that mysql_query can be called without a sql handle but then it will basically use whatever handle you got from the last mysql_connect. What if I wanted to set that default handle myself, how do I do it?
I just want to make it clear that we have all our code written without the handler passed in. We can't change those. We have some code behind the scenes that changes the database between different database clusters. We want to be able to switch between the database without calling mysql_connect repeatedly.
Super ghetto version.
$defaultHandle;
function SetDefaultHandle($handle){
global $defaultHandle;
$defaultHandle = $handle;
}
function q($query){
global $defaultHandle;
return mysql_query($query,$defaultHandle);
}
Try this:
$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_query($query, $dbc);
From manual:
resource mysql_query ( string $query [, resource $link_identifier ] )
link_identifier - The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Rather than pointing you at the manual, which you certainly have read by now based off your question...
You can't do this with the mysql extension.
The magic "pick the last handle opened" behavior is defined by the extension itself. There's nothing you can do to change this behavior.
The behavior you've asked for will require custom code, almost certainly replacing every call to every function with an appropriate wrapper that picks the correct database handle for your load balancing situation.
If you want to provide the connection you can pass it in the function call as the second argument. See documentation of mysql_query for further details.