avoiding multiple attemps to mysql_connect - 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.

Related

error handling if pdo db connection is not present?

I have my db connection parameters set in a single file which I include on all pages I need it. Connection files looks like so... called connect.php :
$db_host = '111.111.111.111';
$db_database = 'test';
$db_user = 'test';
$db_pass = 'test';
$db_port = '3306';
//db connection
try {
$db = new PDO("mysql:host=$db_host;port=$db_port;dbname=$db_database;charset=utf8", $db_user, $db_pass,
array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //PDO::ERRMODE_SILENT is default setting
PDO::ATTR_PERSISTENT => false //when true
)
);
}
catch(PDOException $e) {
error_log("Failed to connect to database (/connect.php): ".$e->getMessage());
}
When I need to do things with the db I include this file and end up with something like this... called example.php :
require $_SERVER['DOCUMENT_ROOT'].'/assets/functions/connect.php';
$stmt = $db->prepare("
SELECT
accounts.account_id,
FROM accounts
WHERE accounts.account_key = :account_key
");
//bindings
$binding = array(
'account_key' => $_POST['account_key']
);
$stmt->execute($binding);
//result (can only be one or none)
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//if result
if($result)
{
// result found so do something
}
Occasionally the database connection will fail (updating, I shut it down, its being hammered, whatever)... when that happens the PDOException I have in the try/catch works as it should and adds an entry into my error log saying so.
What I would also like to do is add a 'check' in my example.php so it doesn't attempt to do any database work if there is no connection (the include file with my connect script failed to get a connection). How would I go about this and what is the preferred method of doing so?
I'm not sure of the correct way to 'test' $db before my $stmt entry. Would there be a way to retry the connection if it was not set?
I realize I can leave it as it and there would be no problems, other than the database query fails and the code doesn't execute, but I want to have more options like adding another entry to the error log when this happens.
To stop further processings just add an exit() at the end of each catch block, unless you want to apply a finally block.
try {
//...
} catch(PDOException $e) {
// Display a message and log the exception.
exit();
}
Also, throwing exceptions and true/false/null validations must be applied through the whole connect/prepare/fetch/close operations involving data access. You may want to see a post of mine:
Applying PDO prepared statements and exception handling
Your idea with including db connection file I find good, too. But think about using require_once, so that a db connection is created only once, not on any include.
Note: In my example I implemented a solution which - somehow - emulates the fact that all exceptions/errors should be handled only on the entry point of an application. So it's more directed toward the MVC concept, where all user requests are sent through a single file: index.php. In this file should almost all try-catch situations be handled (log and display). Inside other pages exceptions would then be thwrown and rethrown to the higher levels, until they reach the entry point, e.g index.php.
As for reconnecting to db, How it should be correlated with try-catch I don't know yet. But anyway it should imply a max-3-steps-iteration.

Is PDO database connection secure?

I am trying to connect to my database with the following code. And it works, but I am not sure how secure is it. Do I must have a private function too? I don't have any examples of how to apply a private function on this code.
$username = 'user';
$dsn = 'mysql:host=localhost; dbname=register';
$password = 'somepassword';
try{
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $ex){
echo "Connection failed ".$ex->getMessage();
}
Better use php composer where you can put these details in a environment file .env. It will be secured as .env is hidden and is placed on Server.
Put the connection parameters into a secure place (i.e. not reachable
by HTTP requests, something like the first answer will be nice), don't leave them into PHP script or some file in the same context... if you put there, protect it with htaccess DENY directive
Never echo exceptions into script output, always deal with them (put
into a log file, translate to friendly errors hiding parameters,
etc). The script never should throw exceptions to the user, it must be handled... the user must only see friendly messages from the script, even a "Ops, something bad happen here..." is better than a "ERROR: SQLSTATE[42000] [1049] Unknown database 'users'" (that show the user a part of the database structure, witch is a security problem)

Cannot connect to MYSQL in MAMP using PHP

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.

Connecting site to phpMyAdmin database

I have a website that has forms, images, text, etc. I want extract data from the forms and keep a record of them in mySQL. In order to do this do I need to change the file extension from '.html' to '.php'? And if so then will this effect any inline css?
Also, when I need to connect to the server via the php, how to I know the database username, database password, and the database host?
I have go daddy as the web host, and use the CPanel they provide to access the phpmyadmin
Thanks - any help is highly appreciated!
This is the PHP code I have so far, and I keep getting error alerts when I run the test through XAMPP:
mysql_connect() is already deprecated please consider using mysqli or PDO.
PDO . database connection example :-
You should create a separate class containing the functions for basic operation in database and keep that file separate from your other code , just inherit the class and use the connection and function .
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
As the other answer stated, use pdo or mysqli instead of 'mysql`.
A good way to use PDO is to put the connection code within a file, and include this file anywhere you need to make use of the database.
Let's call this file dbconnector.php.
try
{
$conn = new PDO($connectionString, 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Now, wherever you want to use database, just use :-
include 'dbconnector.php'
Now, you can access the connection variable via $conn.
Read more on PDO.
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html

php database connection?

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.

Categories