Connecting to a database with PHP and MySQL - php

I know how to establish a connection with a MySQL database with PHP, but I just have a simple question.
When you do this:
$connection= mysqli_connect(parameters);
is the connection established then, or when you do this:
mysqli_query($connect, other parameter);
I only ask because I am unsure, because when you set the $connection variable, aren't you also calling the mysqli_connect() function?

mysqli_connect()/new mysqli() establishes the connection and returns identifier and you cannot run a query before connecting.
Next time you could do some reseacrh - there is so much information on this topic.
Make sure youre aware of the SO FAQ

The connection is established when you call $connection = mysqli_connect(parameters) (Which is deprecated, you could simply use $connection = new mysqli(parameters);)
And it lasts until you close it with mysqli_close()

Related

mysql pdo connection is not closing?

In my php script, When I am executing query on certain PDO mysql connection, on checking mysql logs, I am not able to see the connection getting closed.
Php Code:
?php
$db = new PDO('mysql:host=HOST;dbname=DB',USER,PASSWORD);
$db->exec("SHOW TABLES");
$db = null;
?>
Mysql logs:
180312 18:31:45 9048429 Connect USER#HOST on DB
9048429 Query SHOW TABLES
Though, when I remove query, I can see the mysql connection closed on the Mysql log.
php code:
?php
$db = new PDO('mysql:host=HOST;dbname=DB',USER,PASSWORD);
$db = null;
?>
Mysql log:
180312 18:33:54 9048515 Connect USER#HOST on DB
9048515 Quit
I have to close mysql connection explicitly on my script to prevent too many connections. How can I do the same?
With the above code, Mysql connection was getting closed successfully. Its just that quitting connection was not appearing on Mysql logs.
When I checked Mysql processlist, It was verified that connection was closing successfully.
In addition to the above problem, if there are query statements to be executed using pdo, then pdo statement handler object need to be destroyed too to close mysql connection as stated in php-mysql-pdo-connection-not-closing-without-destroying-statement-handler.
As stated in the documentation: "Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends."
So in your case setting $db=null; should do the trick

PHP MySQL Get Connection From Require() File

I usually am immersed in the Microsoft Stack but dabble in PHP from time to time. A long standing question I've had with PHP that I've never seem to be able to find the answer to is how do you apply your already declared require("dbConnect.php") database connection to your mysql_query()? For clarification please see my code example below:
require("dbConnect.php");
$db_host = 'localhost';
$db_user = 'UserName';
$db_pwd = 'Password';
$database = 'DbName';
$table = 'tblQuote';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT QuoteID, FirstName, LastName, PhoneNumber, Email, QuoteDate FROM tblQuote ORDER BY QuoteDate DESC");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
So in looking at this you can see the standard require() declaration at the top... which already holds my connection info. But every single MySQL Query example I've ever found always creates it's own connection... which I get for demonstration purposes... but I've never been able to figure out how I can use my already existing connection thereby bypassing rewriting the exact same connection info over and over again when it comes to writing queries. I know for you PHP developers this question is like 101 but I've not been able to find an answer to this seemingly basic question... admittedly I may be asking the question wrong so any help would be appreciated!
From the PHP documentation: http://php.net/manual/en/function.mysql-query.php
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
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.
So since you've already created one in your dbConnect.php, the one you just made will be used (It won't create a new one for every query). To pass it explicitly into your mysql_query function call, you can return the MySQL resource that was returned from your mysql_connect call like so:
dbConnect.php
return mysql_connect(....);
Then in the code you pasted above:
$mysql_conn = require('dbConnect.php');
...
$result = mysql_query('...', $mysql_conn);
Then you will explicitly have the connection and pass it to your query - there will be no mistaking it, regardless of how large your codebase becomes. When you require the file, you'll have access to the connection variable, but in the above example, how you get the connection is more semantically clear.
Also, notice that this function has been deprecated in PHP>=5.5, so you'll want to use PDOs or MySQLi which have future support.
Hope this helps!

Connecting to a mysql database without keeping details in the script

I am attempting to create a separate login file for database connections as I am not too fond of having all the access details on each page that requires database access.
I have created a separate file on my server that contains the variables required for a successful login and then use the;
include_once('path_to_file/filename.php');
to get the variables and then use;
$dbconnection = mysqli_connect("$hostname","$username","$password","$database") or die ("Could not connect to the server");
but the connection fails every time. I tried including the connection script in the file I am attempting to include but then I get this message:
Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2)
I'm not really sure how to fix this, but every page in my server more or less access the database and I think it has to be a security risk having login details replicated everywhere!
Anyone have any suggestions or alternatives?
databaseloging format is:
<?php
# parameters for connection to MySQL database
$hostname="hostname";
$database="databasename";
$username="username";
$password="password";
?>
P.S. I have also tried require and got the same result.
Also when using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
http://www.php.net/manual/en/function.mysql-connect.php

PHP - Best way to connect to database when there are multiple connections

I have just recently acquired the service side of a medium size project. The former developer has all of his functions as separate php scripts instead of classes (func1.php, func2.php, etc)... All these 'functions' make a reference to mysqli_connect via referencing the actual
'databaseonnection.php' file. This is creating a new connection every time any of the scripts run (every time I have to call a function) and I don't want to do that. I was thinking about having a persistent connection, but I'm worried about it getting out of hands as the project is growing more and more every day. So, has anyone ever encountered a similar situation? What is the best way to handle my connection to the database? Any suggestions would be greatly appreciated.
From the docs for mysql_connect. 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.
EDIT: I'm sorry I thought you wanted connectivity help. There is no way except to move all those "functions" into one file where the connection is for them only.
I create a con.php file where my PDO connection is established then include that file anywhere you wish to use a connection Here is the base for a PDO connection:
$PDO = new PDO("mysql:host=localhost;dbname=dbname", "user_name", "password");
Here is my notes on using the PDO object to make prepared queries. There is more than you need below but good luck.
Within your PHP file that needs a connection:
1: include('con.php');
2: $datas = $PDO->prepare(SELECT * FROM table WHERE title LIKE :searchquery);
// prepare method creates and returns a PDOstatment object ( print_r($datas); ) which contains an execute() method
// PDOstatment object has its own methods ie. rowCount()
// $datas->bindValue(':search', '% . $search . %', )
// Optional - Manually bind value. see http://php.net/manual/en/pdostatement.bindparam.php
3: $datas->execute( array(':searchquery' => $searchquery . '%'));
// pass in values that need to be bound AND EXECUTE.
// There are 17 ways to "fetch" data with the PDO object.
4: $datas-fetchALL(PDO::FETCH_OBJ);
close a pdo connection by the handle:
$PDO = null;
I think you'll be much better off using PDO as opposed to the old MYSQL functions e.g. mysql_connect. It's much more robust an interface.
Below is the basic code to do this:
$db_handle = new PDO("mysql:host=".$db_host.";dbname=".$db_name.";port=".$db_port."", $db_username, $db_password, $connect_options);
where $db_handle is the PDO object representing the database connection, $db_host is your hostname [usually localhost], $db_name is the name of your database, $db_port is the database port number [usually 3306], $db_username and $db_password are your database user access credentials, and $connect_options are optional driver-specific connection options.
To enable persistent connections you need to set the driver-specific connection option for it before opening the connection: $connect_options = array(PDO::ATTR_PERSISTENT => true); then execute the earlier database connection code.
You can get more information on this from the PHP Docs here: http://www.php.net/manual/en/pdo.construct.php and http://php.net/manual/en/pdo.connections.php.
Regarding creating persistent connections, I would suggest that you close every database connection you open at the end of your script (after all your database operations of course) by nullifying your database handle: $db_handle = NULL;. You should do this whether you opened a persistent connection or not. It sounds counter-intuitive, but I believe you should free up any database resources when your script is done.
The performance disadvantages of doing this [from my experience] are neglible for most applications. This is obviously an arguable assertion and you may also find the following link helpful in further clarifying your strategy in this regard:
Persistent DB Connections - Yea or Nay?
Happy coding!
if you have very complex project and need big budget to re-design, and prefer very simple alteration then
1) stay in mysqli_connect
2) move the database connection to header of your script.
3) remove the function databse close() on that functions.
4) remove the connection link variables, it wont needed for single database.
5) close the database on end of footer.
By this way, database connection establish when starting your script and after all queries, it will be closed on footer. your server can handle the connections without closing/re-open by using keepalive method. basically default keepalive value is 30 to 90 seconds.

Do SQL connections opened with PDO in PHP have to be closed

When I open a MySQL connection in PHP with just PHP's built-in MySQL functions, I do the following:
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
//queries etcetera
mysql_close($link);
When I open a connection with PDO, it looks like this:
$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries
Do I have to explicitly close the connection like I do with mysql_connect() and mysql_close()? If not, how does PHP know when I'm done with my connection?
TIA.
Use $link = null to let PDO know it can close the connection.
PHP: PDO Connections & Connection Management
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
PDO does not offer such a function on its own. Connections via PDO are indirectly managed via the PDO objects refcount in PHP.
But sometimes you want to close the connection anyway, regardless of the refcount. Either because you can not control it, need it for testing purposes or similar.
You can close the Mysql connection with PDO by running a SQL query. Every user that is able to connect to the Mysql server is able to KILL at least its own thread:
/*
* Close Mysql Connection (PDO)
*/
$pdo_mysql_close = function (PDO $connection) {
$query = 'SHOW PROCESSLIST -- ' . uniqid('pdo_mysql_close ', 1);
$list = $connection->query($query)->fetchAll(PDO::FETCH_ASSOC);
foreach ($list as $thread) {
if ($thread['Info'] === $query) {
return $connection->query('KILL ' . $thread['Id']);
}
}
return false;
};
$pdo_mysql_close($conn);
Related Mysql Documentation:
13.7.5.30. SHOW PROCESSLIST Syntax
13.7.6.4. KILL Syntax
Related Stackoverflow Questions:
PHP PDO close()? (Apr 2012)
When the PHP script finishes executing, all connections are closed. Also you don't have to explicitly close your connection with mysql_close().
You can also limit your connections to within local functions. That way the connection is closed as soon as the function is completed.
Well seeing as the $link for the PDO is assigned an object, PHP would set that as null as soon as the script runs so that it's no longer an object. Therefore you could just do:
$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries
$link = null;
http://uk3.php.net/pdo
From what i gather i could not see anyway to close it in the php manual, and examples of scripts i quickly looked at never closed the connection in anyway from what i could see.

Categories