im wondering what is the best and safest way to make a connection to a database to include in all the php files where i have to get data from the database. right now i always make a connection every single time lets say i use a while to get some data from a certain table from database that looks like the code below. Can you guys tell me what is the best way to make a connection and use it for the while?
How i make a connection for the while now every single time
$id=$_SESSION['id'];
$connect = mysql_connect("localhost", "username", "password");
$select_data = mysql_select_db('databasename', $connect);
$select_data = mysql_query("SELECT * FROM members WHERE `id`='$id'") or die(mysql_error());
while($fetch=mysql_fetch_assoc($select_data)) {
// Show profile pic.
$oImgBox = $dom->getElementById('adminProfilePicture');
$oImg = $dom->createElement('image');
$oImg->setAttribute('src',$fetch["profilepic"]);
$oImgBox->appendChild($oImg);
As others have mentioned, you obviously need to use either mysqli or prepared statements. But with that aside, if I am understanding correctly, I believe what you are looking for is the include() function.
With an include, you are able to put a particular script (such as db connection), on every page that requires it easily. See here http://php.net/manual/en/function.include.php
The first step is putting your PHP code into a standalone php file, such as db_connect.php or in your case user_profile.php. Then, for every page you need to make a connection to the database, you would add include 'user_profile.php';
above your html.
EDIT - Adding sample DB connection script.
$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}