i have a few question on php db connection and hoping someone can answer them all, when i create a db connection using pdo, like below
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
is this connection always created when someone refreshes the php page?
or does it check if that connection is already open and then use that connection instead?
how would i be able to close that connection when i am done with it?
yes
nope. It tries to utilize previously established connections only if you have set up permanent connections
generally you don't need to do anything special. php does that as long as your script ends
I found this in the php manual. Hope it helps.
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.
Related
I'm using Jetbrains and Mysql to work on this practical project, but when I connect to the mysql
database it gives me the following error:
C:\wamp64\bin\php\php5.6.40\php.exe C:\wamp64\www\Social_Network\Includes\connection.php
Connection failed: SQLSTATE[HY000] [1049] Unknown database 'social_network'
Process finished with exit code 0
I made sure several times that the database name is the same name and there are
no spelling errors at all (I copy pasted it from the database)
Here's my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=social_network", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//?>
Welll, there's little that can be done about it. MySQL thinks that the database does not exist.
is the server the correct one?
is the case sensitivity set correctly? "Social_Network" and "social_network" might be considered different.
can you access the database with those parameters using a different tool (e.g. HeidiSQL, SQLYog, SQLterm, in a pinch even phpMyAdmin)?
Actually, JetBrains PHPStorm has a SQL terminal utility that can diagnose the connection. You may want to use it (once it knows what database you're connecting to, it will also warn you of several possible errors such as using the wrong table name or column name).
I just installed MAMP and have created a MYSQL database. I can access it via PHPMYADMIN.
In my php page I have this, pasted directly from the MAMP webstart page--
$user = 'root';
$password = 'root';
$db = 'local_db';
$host = 'localhost';
$port = 3306;
$link = mysql_connect(
"$host:$port",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
The resulting page stops at this point, won't print anything below these instructions.
I've tried changing the port in the MAMP preferences. I also included or die("Could not connect"); after the first line, but still don't get any text after the link data in the page.
I checked online, and others with the problem at least see the die text. I don't get that.
I haven't changed any passwords or data other than mess with the port number.
Any help would be appreciated!
Please give the following a try, I have developed and tested it locally, functionality within has been documented to help you understand what is going on in every step.
/**
*
* Modern method of connecting to a MySQL database and keeping it simple.
*
* If you would like to learn more about PDO,
* please visit http://php.net/manual/en/book.pdo.php
*
*/
//Set up database connection constants, so they cannot be changed.
define('DBHOST','127.0.0.1'); //Change this to the ip address of your database
define('DBNAME','test'); // Change this to the database name you are trying to connect to.
define('DBUSER','databaseuser'); // Insure this user is not the root user!!!!
define('DBPASS','databasepassword'); // Insure this is not the root password!!!!
//Let's try to connect to the database first.
try {
//Initiate a new PDO object called $MYDB and pass it the proper information to make
//the connection
$MYDB = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME."", DBUSER, DBPASS);
//If we are successful show it :D for the test page, if this is for production you should not show this.
echo "Database connection was successful.";
//If this does not worth catch the exception thrown by PDO so we can use it.
} catch(PDOException $e) {
//Show that there was an issue connecting to the database. Do not be specific because,
//user's do not need to know the specific error that is causing a problem for security
//reasons.
echo "Oh, sorry there was an issue with your request please try again.";
//Since we had an issue connecting to the database we should log it, so we can review it.
error_log("Database Error" . $e->getMessage());
}
//Since this is 100% php code we do not need to add a closing php tag
//Visit http://php.net/manual/en/language.basic-syntax.phptags.php for more information.
If you have any issues with this please attempt to break it up into smaller pieces while reviewing the PDO documentation.
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
File : Config.php
<?php
require 'inc.database.php';
// Checking if there already a connection. If not then connect to the database.
if(!$IsConnected){
$Database = new Database();
$Database->connect("localhost", "aih786_raheel", "raheel786", "aih786_basicblog");
$IsConnected = TRUE;
}
?>
I m using my config file on my every page because on every page i need to have my database object. Thing i want to clear is that by this approach can i avoid multiple attemps to connect to the database as it is not a good practice to make same connection again and again.
Lets say i have a login page which is the first page of my cms. The connection will be opened on the login page and now when i move to the dashboard.php page i require the config.php file in this page too...so by this it won't create the connection and object again.
Pleas tell me is this the right approach to achieve my goal and also will it give me the access to the object $Database ? I'm not sure if we can use the object on differnt pages once it has been created on first page.
A very rudimentary approach would be to define a function that returns a database connection on-demand, e.g.:
function getDefaultDatabaseConnection()
{
$db = new Database;
$db->connect(...);
return $db;
}
Usually, I try to fire up one connection per page load that needs it.
If I have the proper variable already stored in SESSION variables, then oftentimes
it is not necessary to fire one up.
Given that, I do consider it proper form to drop the connection object at the end
of the script that called it.
And Jack is right, I use a function to fire up the connection.
function dbConnect_readOnly() {
$host="127.0.0.1";
$user="*********";
$password="********";
$dbname="**********";
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "Unable to connect to database.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
return $DBH;
}
and to close:
function dbClose_connection($DBH) {
$DBH = null;
}
Include the script at the top of every page that eeds connectivity just after you check for session variables.
I'm currently writing a PHP application and i noticed that my page loads kinda slow. I takes about 2 seconds (2.0515811443329 to be exact).
I've tracked down what the bottleneck was and it's the part where i'm creating a PDO connection to my MySQL database.
My 'connect()' method doesn't do any exoctic stuff. It simply looks like this:
public function connect ( $database, $host, $username, $password )
{
try
{
$this->db = new \PDO("mysql:dbname=".$database.";host=".$host, $username, $password);
if ( !$this->db )
{
throw new \Exception('Failed to connect to the database!');
}
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
catch ( \Exception $e )
{
echo '<strong>Exception: </strong>'.$e->getMessage();
return false;
}
return true;
}
So when i comment out the call to the 'connect()' method, then my page loads in: 0.035506010055542
This is a huge difference. I can imagine that creating a connection to a database does take up some time, but it takes more than 1,5 seconds... I'm not sure if this is normal?
If it is normal, that it takes up that amount of time then is there a way to store the database connection? Like putting it in a session? Actually, as far as i know storing it in a session isn't possible. But it would be the ideal solution. Storing the connection somewhere until the user closes his browser.
In anyway, is there a problem with my PDO / MySQL? And can i simply store the connection resource somehow? So that i don't have to reconnect to my database everytime for every new page?
PS. I'm doing this all on a localhost (Windows).
You're probably making a connection with 'localhost' as address. Try to change that to '127.0.0.1'. That should fix the problem.
You can create a persistent connection to database using PDO. From the manual
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
And example:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>