PHP5 mysqli vs mysql config files - php

I know this sounds very stupid indeed, but I find mysqli prepared statements and its object-oriented approach attractive so I plan on converting some of my past doodles from mysql to mysqli.
Here it is... The question
In mysql I used to have a configuration file, for example included in every file that needs the database (i.e. require('sys/dbconfig.php');)
I am not sure if I need to do this in mysqli, or do so as others say, open a connection when you need it, close it when you don't need it (i.e. stick $mysqli = new mysqli($host, $user, $pass, $database); everywhere it needs database transactions.

I do it like that:
config.php
define("DB_HOST", "127.0.0.1");
define("DB_NAME", "demo");
define("DB_USER", "root");
define("DB_PASS", "root");
database.php
// include database constants
include_once("config.php");
// create db connection
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
now you can make SQL statements via
$result = $db->query("SELECT x FROM y;");

MySqlI comes in 2 flavours: procedural and object oriented.
When you use the procedural style everything stays the same as in mysqli_.
You are refering to the object oriented style and there the configuration is different .. more object oriented actually. That means that you have to create a new instance of mysqli and use its methods to get the job done.
Note: when using mysqli_ the same way as mysql you will have the same problems with SQL injection. You should use mysqli in combination with prepared queries and parameter binding.

Mysqli opens the connection when it is instantiated with new mysqli(...) (so does PDO).
During a PHP session you should not need to open/close connections to the database because the duration of a PHP session (for normal websites/webapps) is less than 1 second.
Forcing the equivalent of mysql_connect/mysql_close multiple times in the code can be helpful only in long running scripts that do not need an active connection for their entire duration.
The number of separate mysql connections allowed per mysql user is limited depending on the configuration of you server.
If you have some script that runs a long time and that will likely intersect many other scripts, you may use-up all of the allowed connections per user and thus block other users.
I would suggest (as a simple approach) to instantiate mysqli in a file that you will include everywhere you need db access use the variable you stored the mysqli object everywhere you need it using global $db.

I tend to create constants in a config file like Panique does.
I also create an App class with a static method fetch_db that contains the code for the connection. Then whenever I need a db connection I just call App::fetch_db().
I can post the code and a little more explanation later this afternoon when I get home.

Related

PHP PDO new connection: What effect does selecting the database have?

When making a new connection with PDO:
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
It appears you have to specify a database in the DB_DSN, e.g.
mysql:dbname=mydatabase
I have however just discovered that this does not limit subsequent queries using this connection to just this database. Any other databases that DB_USERNAME has permissions for can be used. All it appears to do is specify a default.
It has revealed for me that sometimes, queries were not being specific enough and thus a risk that a table in the wrong database would be accessed.
I am thinking I should create a dummy database, make all connections to that database, thus forcing all queries to include the database name explicitly.
Or: is there a way to make a connection exclusive to a given database?
What is best practice here?
Options on that:
use db name in querys SELECT * FROM dbname.tblname
create an sql mapper class that selects the database before each query new SQLMapper($databasename,$connection); & mysql_select_db($this->dbname,$this->con) in query() method
use DOCTRINE or something like that, they handle that for you
give an dbuser only access to one database (forces devs to use the right instance & no db change)
Use what is usefull in given cases, there is no best solution.
Its mostly about how much control over the code in your application you have.
If rules are followed, then everything should be fine.

How to force the creation of a NEW DATABASE CONNECTION using PHP's PDO to connect to MySQL

I use PHP to connect to MySQL.
At last, I switched to the PDO interface from the deprecated mysql_! I love it, and it works great, but one lingering issue...
MY QUESTION: Does a new PDO (using the same credentials) always create a new connection to the database?
If that's the case, then I'm all set!
I am aware of the option of "Persistent connections" in PDO; I do NOT use that option.
With the old mysql_connect() function, I could FORCE a new database connection with the new_link flag. Am I correct in my understanding that with a new PDO, one ALWAYS gets a new database connection? (Unless requesting a "persistent connection" - which, once again, I do NOT do.)
If I understand correctly, PDO is the opposite of mysql_connect in that (assuming identical database credentials) PDO always gives a new connection, unless specified otherwise (i.e. unless requesting a "persistent connection") - WHEREAS by default mysql_connect would give the same old connection, unless you forced a new one.
Side note: as to WHY I want to force a new connection, it's part of my implementation of a more robust SQL query execution mechanism. I discovered over the years that, when a PHP script is used to serve large files, occasionally a new SQL query gets a lost database connection error ("the database has gone away"); in those cases, my remedy - which worked perfectly for years - has been the following algorithm:
1) try to run the SQL query
2) in case of error, force a new database connection [critical step!] and then re-run the SQL query. It if fails a 2nd time, give up and issue an error/log; but, in most cases, the problem goes away and the 2nd attempt works :)
I'm trying to replicate that robust function with PDO... I found excellent guides on the mysql -> PDO switching (such as http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ), but I'm still hazy whether instantiating a new PDO object implies a new database connection in cases where an earlier PDO object was created with the same credentials.
Thanks!!
Yes it's a new instances of the connection using the credentials given. You can see this with MySQL SHOW FULL PROCESSLIST via MySQL command-line, as it creates each new connection and query, just have to be fast about it or run some slow queries.
On a side note; running the insert again is a bit dirty workaround to an unoptimized process with the database design and mysql config, I recommend revisiting the items in question and find a better method to the process. Best

Already using mysql_connect--should I also use mysqli_connect?

First, some background: I am working on a pre-2000 website that uses mysql_connect and mysql_* functions everywhere. It is not feasible to simply replace all of these at the moment.
I do, however, plan on slowly making the change to mysqli_* functions. I have run into an instance where I need to use mysqli_multi_query though, and was wondering if it would be better to:
Create a function that opens and closes the mysqli connection, while performing one mysqli_multi_query.
Create a function that opens a mysqli connection when needed, and only open the mysqli connection only on pages that need it.
Simply use the mysqli_connect() function the same way I am using the mysql_connect() function and have both connect at the beginning of my scripts and close at the end, on all pages.
The trouble I am having with deciding on these is that 1 limits the number of multi-queries I can do on one page (while also adding to the future code-cleanup that needs to be done), 2 also adds to the code-cleanup, albeit not quite as much as 1, and 3 might be either inefficient, or unsafe, although I would be able to clean-up as I run into the old queries.
This website gets over 1 million visitors per month.
Anyone know what would be "best-practice" in this scenario?
"best practice" seems to be to use PDO for your MySQL connections, according to recent articles turned up during a search on the topic (for example https://phpbestpractices.org/#mysql ) although I couldn't find any specific guidance on when to open those connections if they are not strictly required on that page.
I'd suggest going with your second choice, as the abstraction makes code more manageable and maintainable in the future, for you and for other devs. As far as I know, there is no specific drawback to using mysql_* and mysqli_* functions side-by-side, and it is recommended to use mysqli_* over mysql_* in all cases
( see http://www.php.net/manual/en/mysqlinfo.api.choosing.php, the section under 'recommended API').
However your code will not be as secure as it could be until you complete the transition.
I would say that whether or not to open connections when they are not strictly required is a judgement call for you to make - I'd lean towards only opening it when you need it on general principles of efficiency, however in practice when dealing with legacy code it may prove far more trouble than it's worth. If it doesn't slow your server down too much you could live with it, so long as you recognise it's not the most efficient way to go.
PHP offers three different APIs to connect to MySQL: mysql(outdated), mysqli, and PDO extensions.
You don't need to connect to the database on every request.
mysqli_connect() with p: host prefix
//or
PDO::__construct() with PDO::ATTR_PERSISTENT as a driver option
http://www.php.net/mysql_pconnect
In your case, I would use PDO type connection implemented as the singleton pattern with "permanent" connection options.
Included on top of the every script.
class Database {
private static $instance;
private $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
private $user = 'dbuser';
private $password = 'dbpass';
public static function getInstance() {
if(!self::$instance) {
self::$instance =
new PDO($this->dsn,
$this->user,
$this->password,
array(PDO::ATTR_PERSISTENT)
);
}
return self::$instance;
}
}
That way you can get database instance with:
Database::getInstance();
...and don't flame me for using singletons in the legacy app! ;)

Architecture needed to reduce mysql connections in AJAX/PHP/MYSQL

BACKGROUND:
I am passing variables through AJAX to php file. The php file connects to a server and retrieves the result which it passes back to javascript. This happens every time a user clicks on the request button (about every 5 secs). Thus for each user, the php file (and so the mysql connection) is called once every 5 secs.
ISSUE:
As is apparent above, the number of mysql connections are impractically high.
QUESTION:
Is there a better architecture where instead of having so many mysql connections, I can rather have fewer connections.
I have read a little bit about mysql_pconnect. But what happens if I have to upgrade since I read somewhere that mysqli doesnt support it? How many queries can a single mysql_pconnect handle? If anyone suggests mysql_pconnect then how to implement it?
Is there a better architecture where instead of having so many
mysql connections, I can rather have fewer connections.
Don't really know, but I think that for you the proposed pconnect is the best available option. Unless you have either mysqli or PDO_mysql available now?
I have read a little bit about mysql_pconnect.
But what happens if I have to upgrade since I read somewhere that mysqli doesnt support it?
You would probably need to change method when upgrading beyond PHP 5.5.
How many queries can a single mysql_pconnect handle?
Unlimited, as long as the connection is kept alive. If there are no available free connections a new one is created.
If anyone suggests mysql_pconnect then how to implement it?
Change your current mysql_connect calls to mysql_pconnect. That should be all.
What you are looking for is singleton design pattern for database connections. But it has it's trade off too. Example code for singleton design for database would be as below.
define('DB_NAME', "test");
define('DB_USER', "root");
define('DB_PASS', "rootpass");
define('DB_HOST', "localhost");
class Connection{
private static $connection_;
private function __construct(){
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME, $con);
Connection::$connection_ = $con;
}
public static function getConnection(){
if( !Connection::$connection_ )
new Connection;
return Connection::$connection_;
}
}
$con = Connection::getConnection();
Read more
php singleton database connection, is this code bad practice?
How static vs singleton classes work (databases)
You can find tons of example and information if you google. Hope this helps

PHP & PDO: One Connection vs More-than-one Connections

In my PHP program I need to hit the database between 0 and 3 times on any given webpage request. I am using PDO to interact with MySQL. First I create a database connection using something like this:
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
Then I do what I need to do and close the connection like this:
$dbh = null;
I open and close a connection 0-3 times right now, the same number of times I need to interact with MySQL.
My question is, should I be re-using this connection instead? My queries are not one after another, they are scattered throughout my program and I don't really think it would be easy to run them one right after another.
So is it better to create a new database connection and close it for each interaction (query) or to just leave the connection open and reuse it? Does it make any difference?
Thanks!
For a typical website page, you should be reusing the same connection for all queries.
It's not worth it to spend time disconnecting and reconnecting.
Unless your pages take a huge amount of time to run (huge being relative), then there's no point in relinquishing a connection. You'll end up wasting more cycles on connectiong/disconnecting than you do actually executing queries. MySQL's pretty lightweight as far as connections go, but it still adds up.
The site says: "You must have 50 reputations to comment". My reputation is pretty bad so I can't leave a comment, but I want to add a notice on:
For a typical website page, you should be reusing the same connection
for all queries.
Absolutely right, but in case of need atypical script (e.g. compare tables between a remote database and local database) one can't use the same connection. Must close first connection and establish new one or have 2 separate connections (using different names) at the same time.
I prefer the second option in this case because of closing connection using "$dbh = null;" it can be a bit difficult in some cases. (PDO closing connection)
Here is explanation [from documentation: https://www.php.net/manual/en/pdo.connections.php ] why should be careful with "$dbh = null;" (it should be closed all instances too):
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here
$sth = $dbh->query('SELECT * FROM foo');
// and now we're done; close it
$sth = null;
$dbh = null;
?>
So, only $dbh = null; (without nullifying instances) is not a good idea.

Categories