2 require_once On Same File Create MySQL Connect Issue - php

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.

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?

When do I have to close mysqli (Database) connection?

For now, I have one connect.php file e.g.
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = new mysqli(
$mysql_host,
$mysql_user,
$mysql_password,
$mysql_database
);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
In every other PHP file that uses MySQL queries, I use "include 'connect.php';"
For Instance on W3Schools, they create for every query a new connection and then close it after use. See here: w3schools.com: I'm not sure if they do it just for showing purpose, or if it is best practice to do it this way.
Do I have to close the connection after each selection and then establish a new one, for the next query? If not, when do I finally have to close the connection? On the end of the PHP File with all the queries?
A quote from the php.net site.
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.
Source: http://php.net/manual/en/mysqli.close.php
Close the connection when you are done using it for that page. If you have, say, a blog, the button that you use to post it would start the code that would open the connection, do some work with the connection (like adding it to your db and or showing it on a page) and then it would close the connection so that it isn't open any longer than it needs. But when you click the button again it would start the process over, only using resources as it needs them.
Best practice is to use close function in footer.php

PHP Prevent multiple MySQL Connections

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

Do I need to use mysql_close(connection)?

I have the following code in db.php to connect to my DB.
<?php
$DB_HOST = "localhost";
$DB_NAME = "db";
$DB_USER = "user";
$DB_PASSWORD = "pass";
$con = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($DB_NAME , $con);
?>
In my other script I include it using:
include("db.php");
In some cases I receive the ff error:
[10-Mar-2012 10:47:20] PHP Warning: mysql_connect() [function.mysql-connect]: User db_user already has more than 'max_user_connections' active connections in /home/user/public_html/sc/db.php on line 8
Now, I am wondering if I need to close the connection like:
<?php
include("db.php");
//other stuff here
mysql_close($con);
?>
BTW, I have a value of 100 max_connections in my MySQL config.
I also research about persistent connection and I believe my code above is not a persistent connection.
No, this won't help you if you close it at the end of the script. mysql_close() is just useful in case you want to free up resources before you end your script, because your connection is closed as soon as execution of the script ends
If you don't close your connections, they will stay open and take up precious resources on the server. I guess there's there the security point too, you don't want to risk someone getting a hold of the connection.
I prefer to put my database in a class and use __construct to create the connection, and __destruct to close the connection. If your unfamiliar with classes. The __construct and __destruct gets called automatically when you create and destroy a class.
Edit:
There was originally meant to be an example. But I have a basic but working mysql class here https://stackoverflow.com/a/9651249/1246494.
It shows the usage of mysql_close and how I was trying to relate it to the class destructor. The point was, any network connection should be closed, whether your database is on a remote server, or localhost.

Database connections and functions?

I'm new to using functions, so - no judgements please ;).
Let's say I have a function add_to_x() in function.php which within performs a mysql_query(). This function is included, (include "function.php";), into script.php, and called mid-way through that script. At the top of function.php I establish a database connection, closing it at the end.
Would this be passed through by default to the function add_to_x() or would I need to establish and close a connection within add_to_x() itself?
For illustration and good measure:
Contents of script.php
include "function.php";
// Do something
add_to_x($arg1, $arg2);
// Do something else
Contents of function.php
include "db_conn.php";
$conn = mysql_connect($db_host, $db_user, $db_pass); mysql_select_db($db_name);
function add_to_x($arg1, $arg2) {
// Do something
$query = "SELECT * FROM table WHERE x = '$arg1'";
$result = mysql_query($query);
}
mysql_close($conn);
Would that work? Or would I need to do something like this:
function add_to_x($arg1, $arg2) {
include "db_conn.php";
$conn = mysql_connect($db_host, $db_user, $db_pass); mysql_select_db($db_name);
// Do something
$query = "SELECT * FROM table WHERE x = '$arg1'";
$result = mysql_query($query)
mysql_close($conn);
}
It might look like a rather stupid question, but I'm not sure of the scope of connections/functions. I feel that perhaps the second example would be better practice even if the first would work?
Any comments, advice, answers would be greatly appreciated! (I realize I've made this question a bit messy, but I hope the illustration code helps, and of course, if you need further clarification please do ask for it)!
You can open the database connection in the file that defines your functions, as you are doing. But closing it at the end of function.php is not what you want to do - by doing this you are closing the connection before it is ever used.
You would either call mysql_close() at the very end of your main script (after all calls to functions that require the connection), or not at all (the resource will be implicitly closed/freed when the script finishes).
Any code that's in the global scope of function.php (ie not inside a function), will be executed when you include the script. So in the code you posted, the $conn will no longer be open in your add_to_x().
Few things to explain:
1) If you have $conn defined in global scope, you can access it from any function using keyword global e.g.
function add_to_x(){
global $conn;
}
2) you can use mysql queries in your functions even if connection is made "outside", as mysql will use last opened connector, unless other specified
summing up, first of your example should work (did not check parsing etc).

Categories