i do have a website which just write and read some data from my database.
for this purpose, i decided to use prepared statements but i have no clue how i can setup this stuff once, without creating them on every call like the database connection.
lets say, you call website.com/write.php.
write.php then "require" "settings.php" to get the database connection.
This causes the connection to be initialized (as the prepared statements too) every time you call something on my website.
How do i pretend this behaviour?
you can use static classes for to achieve that.
You can create a class Database, in a file named Database.php for example. Then in that class you create a static property, for example $connection and a function to load that property if it's empty. Then in your file settings.php you just import that class and use the same connection everywhere by just calling Database::connection->function(..).
However, it's not always a good practice. Maybe you don't even need persistent connection, but auto-initialization of the database connection based on some dynamic settings per user. You can store these settings in sessions and recreate connection with these settings.
Related
I have written a data class for handling MySQL queries and then all other classes such as login, products extend this class to make use of the database. As a result, each page load creates 2 or more DB connections due to something similar to the following:
$login, parent::__construct(); // check login via db
$products, parent::__construct(); // fetch products from db
Is there a way around this such as adding some code in the constructor to verify whether an existing DB connection has already been established?
A fellow developer I work with writes in procedural style and simply uses a single global $_db object for all queries and, this seems a lot more efficient as it only creates 1 DB connection.
For many smaller applications, I make my database instance global to the whole application, along with configuration and other application-wide classes, such as logging. This is not necessarily the preferred method, as it couples code to expect things named certain ways, and could possibly cause conflicts down the road. However, for small utility applications it is convenient.
For anything larger, I usually utilize my DB from an ORM anyway, so it becomes a non issue.
Michael's example of creating a static class and how to use it helped resolve the problem.
https://stackoverflow.com/a/26981461/541091
I'm new to PHP so this question may seem dumb.
When we are connecting a php application to the database, should I put all the connection code and configuration in an separate file and include this file in every php page I have? Or do I only need to put it in index.php and the connection keeps on?
Most connections in PHP are resources, and can be stored in a variable. Whenever you need that connection, you just pass that variable to the function that needs it ( ala $ch = curl_init; curl_exec( $ch ); ). Access to these variables is determined by normal scope rules; If you define the variable and then include a file, the included file has access to whatever global variables the parent defined. If the variable is a property of a class, then it is accessible so long as it is a public property.
You should also note that, as with most things PHP (except for Sessions and Persistent Connections), these resources only live during the lifecycle of the script, namely a single request. If you want these connections to be available for every single request then you should place the code that creates them at a point where they will be created before you need them, exists in a scope that is accessible and allows you flexibility later down the road when something changes (because change is the only constant).
It is possible to create persistent connections. I typically do this using PDO. I usually create a database connection class. The class is a singleton. It establishes a persistent PDO connection and stores it as a protected field. Each of my model classes extend the database connection class, thereby inheriting access to the protected connection member.
I recently switched from ext/mysql to mysqli in a PHP project. In that project, I extensively used the connection reuse feature of mysql_connect by setting the new_link parameter set to false.
As far as I understand, there is no such mechanism in mysqli_connect; it will always return a new connection even though the same host and user is used. Is this correct? Is there some other function that can mimic the reuse-behaviour?
NB: I see that with prepending the host with p: will create a persistent connection. However, this cannot be used in my case, as part of my project relies on temporary tables.
Update:
The actual mysqli object is embedded in a DB handler class which manages access to the database. This handler is always used to interact with the DB.
I oversimplified my problem because I just wanted to focus on the question if mysqli can automatically reuse a single connection by multiple calls to mysqli_connect with identical parameters. My project is an extenstion to a framework and provides multiple entry points and hooks. I cannot control the order or number of function calles from the hosting framework into my extension. Each part of my extension creates an instance of the DB handler, but could reuse the actual underlying connection.
The creation of the DB handler is done though a db-factory. So I will probabely have to implement some sort of connection-caching there myself...
Nope, mysqli ext doesn't follow that lazy mysql ext behavior, and for a reason.
So, you have to always explicitly address mysqli object. The only problem, though, is with variable scope. But as long as you have $mysqli object visible, you can use it all right.
However, there is another problem: you shouldn't address $mysqli object in your application code at all. That was a problem with old mysql ext and it is a problem with mysqli ext as well - it is not intended to be used in the application code as is.
One have to create a some sort of wrapper, to encapsulate all the database related stuff, and in the application code always use this wrapper class only.
So, get yourself such a wrapper, create an instance of it, and then pass into every class and function as a parameter.
I am building a plugin for WordPress 3.3.1. In the code I define several shortcodes, class to support them, and a couple of admin pages. I am at a beginners level with php although I have 20+ years experience with programming, OOA&D, etc..
In the class methods, I make calls to a custom database not housed in the wp database. That is, the custom database is a separate schema, independent of the wp database.
Right now, I make the declaration in the methods that need the object. Works fine for dev but won't cut it in production. I am tempted to raise it to the class instance level. Here is where my question becomes clear. There are several classes that will need the connection. The plugin needs only one connection.
Where is the best place to put the database connection object declaration and initialization?
Given the answer to that, where is the proper place to destroy the db connection object instance?
I would make the database connection a static field. Which class to put it in depends on how you've structured your classes/code. Making it static will ensure that the same connection is shared throughout your script.
I recommend using PDO (connecting PDO to MySQL, etc) to connect to your database. PHP will automatically close the connection when the script ends.
I'm writing some php code, and I'm frequently accessing my MySQL database to read and update fields.
My current code includes a class called dbconnnect, and I use it as follows:
class edit_data extends dbconnect {
//<some php code>
parent::connect();
//<get info from database>
parent::disconnect();
//<evaluate data>
My question - this is the most efficient way to connect and disconnect from a MySQL database? (Keep in mind, I almost always connect to the same database, so no need to redefine the connection parameters every time).
I was considering running the connect in the constructor, so then I could just write
$connector = new dbconnect();
but I realized I'm not actually saving much by doing this - right?
Thanks.
Just make sure that the code for db connection/disconnection is included/run automatically at the start and end of each file, without needing to do it separately for every file. Make sure this code is stored in 1 location and included in all other files, so you can change it easily when needed. As long as you do these things, the rest is just personal preferences for how you want to connect/disconnect from the db.
I would also recommend a framework such as CodeIgniter for taking care of common tasks such as this behind the scenes for each file.
By using
$connector = new dbconnect();
and not
parent::connect();
you are essentially decoupling your edit_data class with the dbconnect class. What the means for you is that:
your edit_data class can now have more than one connection by using multiple dbconnect objects (connection pooling)
your edit_data class can (in the future) use something other than dbconnect and won't have to change any other code. With parent::connect(), if you ever change to extending some another class, you'll have to make sure the new class will support the existing semantics
The "right" way would probably be to do it like the MySQLi and PDO extensions - open the connection in the constructor and close it in the destructor.
The "efficient" way is to check the connection in your query() method and (r)open it if necessary.
In both approaches you avoid creating a separate connect() method, and thus remove the risk of forgetting to call it in your script.
Unless you know you are always going to connect to the database every time, I wouldn't put the connect piece in the constructor. If you don't need to connect, you shouldn't, it's expensive. Your constructor should only accept the connection parameters. Although it looks like you may be using static classes, so the constructor would get executed.
As Krzysztof mentioned, you should connect on demand. In my database class, I have all queries eventually go through an "execQuery" function. That function checks if there is a connection to the database or not.
Having a single central query function also allows you to do things like record all queries that were run in a session, add timing, logging or anything else you need to do.
Having the disconnect in the destructor is the proper place.
Our codebase has many paths and makes a lot of use of caching.
We only connect with the database when the first query is executed. (so actually on the ->query() method).
We let PHP disconnect once the script is over, and don't explicitly call ->disconnect
Juts be sure of reusing you connection:
Review new_link parameter:
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.
http://php.net/function.mysql-connect
I think deriving your "edit_data" class from your "dbconnect" class demonstrates confusion of logic. Is your data editing object a special type of database connection? Or maybe it would make more sense to say the data editing object needs to use a database connection? (This is the difference between IS A and HAS A.)
Although it seems to be falling out of fashion now, you can use a singleton factory call to get the database handler. Then any function which needs it can simply call it. If you make the handler self-initializing the first time it has to do any work, then nothing needs to even worry about initializing it. (To do this, check if the instance variable containing the handle is a resource handle - if not, call the initializer. Remember to decide what to do if the connection fails.) Then you just need a way for the handler to find it's configuration. I would have the factory call do that, not the initializor.
A variant way of doing that is for the constructor to get the current database handler and put a reference to it in an instance variable. This can be done several ways. Requiring it in the constructor might work, or you can fall back on the singleton factory call again. This technique gives the object constructor a chance to deny instantiation if the database handler won't initialize (the factory call can check that).
Connecting is expencive so, don't connect and disconnect for each query.
If possible use mysqli instead of mysql, it is generally faster
If you are using mysql not mysqli, use mysql_pconnect instead of just mysql_connect
php closes all the open db connections, so there is no need to explicitly do so
share connections between queries whether you connect at the start of the script or on the first query is up to.