PHP Prevent multiple MySQL Connections - php

I have a large procedural style php/mysql website, which is splitted into many different files. Within each file, i include my dbconn.php, to ensure, that a db connection is available.
It looks something likes this:
index.php
<?php
include_once ('header.php');
include_once ('nav.php');
include_once ('content.php');
include_once ('sidebar.php');
include_once ('footer.php');
?>
and within each of these files i call several other files via include_once. So in total i come up with about 30 different files.
Every file starts with:
include_once($_SERVER['DOCUMENT_ROOT'].'/dbconn.php');
Since i'm using include_once, dbconn.php should not be loaded more then once, but recently i get following php warning.
PHP Warning: mysqli_connect(): (HY000/1226): User 'username' has exceeded the 'max_user_connections' resource (current value: 20) in /var/www/html/dbconn.php on line 10
My dbconn.php looks like this:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$db = "dbname";
if(!mysqli_thread_id($con)){
$con = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($con, 'utf8');
}
unset($host,$user,$pass,$db);
?>
So there is a double check.
If there already is an open mysql connection, the file should do basicly nothing.
What am i doing wrong?
Why do i get this php warning and how do i reduce the amount of mysql connections?

Basically, it's not different calls from a single page that is leading to the problem. It's the fact that you have multiple OPEN connections at the moment.
Make sure you close you connections after they have served their purpose.
Also, try to avoid the kind of structure you currently have, have all the DB related stuff included in one file and then include it only once on your page.

I solved the problem by using a singleton pattern.
So i changed the mysqli prodecural code into mysqli objectoriented.
i got the pattern here:
http://www.davecomeau.net/blog/1/Single+Database+Object+in+PHP+5+Using+the+Singleton+Pattern

Related

Strange inconsistency, database connection from require_once not working in only one place

I've encapsulated my MySQLi connection logic in a script named connect_mysqli.php. This working just fine all over my project (9 other pages are having no trouble), but one page is returning this error:
Warning: mysqli::query(): Couldn't fetch mysqli in C:\xampp\htdocs\projectName\php_calls\AddItem.php on line 193
Here's the code that's not working in AddItem.php:
$sql = <<<HEREDOC
UPDATE listing_data
SET ebay_id = '$responseObj->ItemID'
WHERE listing_id = '$database_listing_id'
HEREDOC;
require_once(__DIR__ . '/connect_mysqli.php'); //this creates $conn
$conn->query($sql); //this is line 193
And this is the code from connect_mysqli.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$db = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8");
Again, this is working without trouble in every other spot in the project. Here's what I've tried so far:
I checked my SQL syntax. I echoed the SQL query I'm attempting and tested it on the command line, the query is working fine.
Double check my SQL again. I copied the code from a working database call into the AddItem.php. It produces the same error. I tested the original page where this code exists, it works correctly in that spot.
I checked to make sure require_once is working correctly. To make sure my relative path was working correctly, and I am in the cwd that I expected I was in:
echo require_once(__DIR__ . '/connect_mysqli.php');
and it produced:
C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This was expected. I opened Windows Power Shell and ran:
cat C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This displays the code inside connect_mysqli.php! I was beginning to guess my require_once was flawed.
Check to see if there's a naming collision.
var_dump(get_defined_vars());
There is only one $conn.
The connection is not being closed with $conn->close();. If it's closing without my instruction I don't know how or why.
I copied and pasted the code from connect_mysqli.php into AddItem.php and the error goes away. So somehow my require_once must be messing up my connection. AddItem.php and connect_mysqli.php are in the same folder. I tried connecting with this line instead:
require_once('connect_mysqli.php');
I still get an error.
Sorry for the incredibly lengthy question, I wanted to do my research and try everything before creating another question on the topic. For now I can copy the database connection code into AddItem as a workaround, but it's bad practice, and there's clearly some important principle escaping me here that I'd like to understand.
Edit: more information
Nico Haase asked the question that put me on the right track. Line 1 of AddItem.php is a require_once:
require_once(__DIR__ . '\return_item_php_obj_by_id.php');
and inside return_item_php_obj_by_id.php we have the culprit:
require_once(__DIR__ . '/connect_mysqli.php');
//edited out irrelevant code
mysqli_close($conn);
In the original post I said "There's no $conn->close() hiding anywhere." Clearly I was mistaken. I found the hidden close(). When I comment this out, the connection works. Now I've accidentally made my code really hard to read, and I don't want to use a database connection that far away on the stack. Should I leave the connection open so I can use it again with AddItem.php? What's best practice in this case?

How to include two database connections?

I have included 1 database connection in my PHP file. The file that connects to the database is called connect.php. This works successfully with no errors. When I try to include 2 database connections in my PHP file, this is when I encounter errors. It seems as though, I can only connect to one database at a time because only 1 of the databases are connected. Is there a way to include 2 database connections in 1 file?
This is what I have right now:
<?php
require "connect.php";
require "informational-connect.php";
?>
This is what's included in connect.php:
<?php
$db= new mysqli("localhost", "XXX", "XXX", "ARTICLES");
if($db->connect_errno)
{
die("Error");
}
?>
This is what's included in informational-connect.php:
<?php
$db = new mysqli("localhost", "XXX", "XXX", "INFORMATION-DATA");
if ($db->connect_errno)
{
echo die("Error");
}
?>
I am using MySQLi.
In order to have different connections you have to give the connection variables different names
Besides, you need only one database to deal with, and therefore only single connection
The database selection is associated with the connection resource. So you can select it once for each connection.
If you don't call mysql_select_db at all,then all your queries will need to specify explicit database prefixes before all the tables, e.g. select * from db1.table ....
mysqli is provide a functionality for connect multiple database at a time.
But How one single variable in a file can hold two different
connections ?
You should use two different variables for each database connection.
$Db1 = new mysqli($hostname,$username,$password,$db_name1); // connection 1
$Db2 = new mysqli($hostname,$username,$password,$db_name2); // connection 2

How to connect php application to database

I have created register form using php and validation done by using jquery.
I have files are index.php, submit.php and functions.php.
So i need to create config.php to connect database.
I have done to create table in phpmyadmin and created config.php.
Here is my config.php:
<?php
// configuration
$dbhost = "localhost";
$dbname = "crop";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "INSERT INTO crop (fname,lname,email,pass,phone,img,sex-select,dob) VALUES (:sas,:asas,:asafs)";
$q = $conn->prepare($sql);
?>
I am not sure this code correct or not? And i don't know how to include in existing my php files.
I am new to php and now i am learning, can you please help me out to fix this?
Thanks in advance.
To include the connection in other files you simply need to add the following near the top of the other file, before you need any database connection:
require_once 'config.php';
require generates a fatal error if the file is not found and require_once guarantees that the file will only be included once even though you call it multiple times. Since your application will probably not work without a database connection you want the fatal error to let you know that the file wasn't found and it's highly unlikely that you'll want more than one database connection.
There are also include and include_once but in this case you'll want to avoid these because they don't stop the script if the config file isn't found.
PHP documentation:
http://php.net/manual/en/function.require-once.php
http://php.net/manual/en/function.include.php
You have to print the results of the query that you ran.
Check Here on PDO: Prepared Statement
Try this connection code in your web application, your config.php look like
<?php
$Db_host = "localhost";
$Db_user = "root"; //DB User name
$Db_name = "crop"; //DB name
$Db_password = ""; //DB password if you have
$cnn=mysql_pconnect($Db_host,$Db_user,$Db_password) or die(mysql_error());
?>
and after that you can call this file with the help of include or require function in your page.
your submit.php looks like this
<?php require_once('config.php'); ?>

2 mysqli include files on one page

Wondering if it is possible to include two mysqli connection include php files on the same page.
I have a basic site I am using to learn/develop in php with mysql. I have one database for storing user information and another for website specific information. I can use both independently from each other without any issues.
Config.php:
DEFINE("HOST", "127.0.0.1");
DEFINE("USER","root");
DEFINE("PASS","");
DEFINE("DB","sv");
connect.php:
include_once 'config.php';
$mysqli = new mysqli(HOST, USER, PASS, DB);
sec_config.php:
define("HOST", "127.0.0.1");
define("USER", "sec_user");
define("PASSWORD", "");
define("DATABASE", "svn");
sec_connect.php:
include_once 'sec_config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
My php pages can successfully query and display data from these connections. My index.php currently contained included the sec_connect, I am trying to add another php page which (within itself) includes
include_once("connect.php");
When I try and run the page I receive
mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known.
mysqli::mysqli(): (HY000/2002): php_network_getaddresses: ...as above
mysqli::prepare(): Couldn't fetch mysqli in
Fatal error: Call to a member function bind_param() on a non-object in
I have simply commented out the above include_once to get everything working again.
I am using windows with xamp for dev, I have tried accessing via localhost and my ip address and I receive the same error. I have tried editing the hosts file and I have also tried amending the values in the connect files to be unique (changed back as it didnt help).
Hopefully this is the righ question to ask: Is it possible to include two mysqli database connections via different includes from my index.php page?
This should work, provided you refer to the two different connections with different variables (they are two distinct instances after all).
For example:
file1.php
$db1 = new mysqli(HOST1, USER1, PASSWORD1, DATABASE1);
file2.php
$db2 = new mysqli(HOST2, USER2, PASSWORD2, DATABASE2);
file3.php
require "file1.php"
require "file2.php"
$result1 = $db1->query("SELECT * FROM table");
$result2 = $db2->query("SELECT * FROM some_other_table");

2 require_once On Same File Create MySQL Connect Issue

I have this index.php :
<?php
require_once ('required1.php');
require_once ('required2.php');
--- some mysqli_query here ---
?>
what's inside that required1.php is this :
<?php
$DbServer = 'localhost';
$DbUser = 'username';
$DbPassword = 'password';
$DbName = 'dbname';
$con = mysqli_connect($DbServer, $DbUser, $DbPassword, $DbName);
?>
and this is required2.php :
<?php
require_once 'required1.php';
--- some mysqli_query here ---
mysqli_close($con);
?>
the mysqli_close($con); on required2.php makes mysqli_query on index.php failed because the mysql connection already closed by required2.php.
how to make required2.php works independently? I mean, what ever happen on that file (required2.php) leave it there. don't bring anything into other file who calls it, specially the mysqli_close($con);
is it possible with require_once? or PHP have another function to make it like that? thanks!
Use a different connection in require2.php or don't close it. You can also include it at the bottom.
Using mysqli_close($con); in required2.php closes the connection, so after any include of required2.php, $con won't be available.
If you want required2.php to be independent, you have to use another database connection, not $con.
First of all, there is really no need to close the connection in your included file (there may be very specific exceptions...).
If you want to use your second include independently, you should refactor it to OOP. If it is a class that gets its database connection injected via its constructor (dependency injection), it would only show its name to the rest of your code so things that happen in the class or an object, would not affect the rest of your code.
Of course you still should not close your connection as that object will likely be passed around by reference but using objects / classes instead of procedural code will make it more independent an reusable.
if required2.php has nothing to do with your current script, but all you need to do is to run the script as you mentioned, i feel you can call the file required2.php using file(). this will run both the scripts separately and even if you close connection in required2.php it does not effect the current script.

Categories