ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Php Tutorial: How to Access Multiple database from single Function in PHP

Updated on November 9, 2011

In this tutorial, we are going to learn how to access multiple database with an single function without providing password each time as in standard mysql_connect() function. Here, we will connect and select database simultaneously with an single function by merging mysql_connect() and mysql_select_db() in it. By using such method, we can keep our database passwords hidden from co-workers and other private peoples. Well ,hackers doesn't need passwords but this method will help us in keeping our passwords permanent for a long time.

copy the code below (Do Changes as per the requirement) and paste it in a file named as 'functions.php'.

function connect($accept_input) {

$hostname="Address of Database Host";
$username="Username Used to access database Host";
$password="Password to access database host";



function db_test_call() {

	$query=mysql_query("SELECT * FROM table_name");
	echo $fetch['column_name'];

Look at the code above, In the function named connect(),

  1. we are inputting only one value i.e. Database Name,
  2. Then, we are storing all the required info in variables i.e. database username, database paswword, database host and also the database name accepted via function argument,
  3. after which we are executing a query via mysql_query() function and then selecting database,
  4. Then, we created another funtion to test the above connect() function and closing the database connection by just simply typing mysql_close().

Now, create another page with any name in same directory of host and paste the below code in it.




Open the file in which you saved the above code to check if everything is work perfectly. Some of the hosts rename our databases by adding their prefixes or suffixes on our selected name, you can resolve this issue like as show below, 

function connect($accept_input) {

$hostname="Address of Database Host";
$username="Username Used to access database Host";
$password="Password to access database host";

/* Suffix and Prefix before or after database name */ 

$suffix="suffix that you host add after you database name";
$prefix="prefix that you host add after you database name";


If suppose, you want to fetch data from databases that are hosted on two or more domains/servers than you can specify one more argument in connect() function accepting the url/ host_address as value. Like this,

// below $accept_input will store database name and 
// $db_host will store host address or url where your database is hosted
function connect($accept_input, $db_host){


    0 of 8192 characters used
    Post Comment

    No comments yet.