0

I created php script called functions.php in which i've written following codes. It's working fine when i've written "$conn = mysql_connect('localhost','root','pass');" this line. But i want to store these credentials in config file so that it becomes quite easy for me to edit details while working with db. So i created config.php and have written following codes :

<?php
// this is config.php
$config = array(

    'host'=> 'localhost'
    'username' => 'root' ,
    'password' => 'pass' ,
    'database' => 'sample'
);
?>

This is functions.php

<?php
include 'config.php';
function connect($config) {
    $conn = mysql_connect($config['host'],$config['username'],$config['password']);
    return $conn;
}

$con = connect();
if(!$con) die ('problem in connection');

But when i did this then its not working. How can i fix this? Plzz hlp

Raunak Hajela
  • 73
  • 2
  • 10

4 Answers4

0

Your syntax is incorrect, try this:

<?php
// this is config.php
$config = array(

    'host'=> 'localhost',     // Missing comma
    'username' => 'root' ,
    'password' => 'pass' ,
   'database' => 'sample'
);
?>

Also, you don't need to pass $config to function, it will be available globally.

Rohit Aggarwal
  • 650
  • 8
  • 18
0

Why did you add the $config parameter to the connect function? You are not passing any parameter, so $config is always null in your function. Adding the parameter to your call should solve the problem.

$con = connect($config);
Jerodev
  • 31,061
  • 11
  • 83
  • 102
  • thanxx bro this is also working correctly... m using webmatrix while working with php, its not showing any errors if did something wrong... so is der any way to fix this..?? – Raunak Hajela Oct 21 '14 at 07:17
0

Change your config.php to:

<?php
// this is config.php
$config = array(

    'host'=> 'localhost', // comma was missing
    'username' => 'root' ,
    'password' => 'pass' ,
    'database' => 'sample'
);
?>

And functions.php to:

<?php
include 'config.php';
function connect($config) {
    $conn = mysql_connect($config['host'],$config['username'],$config['password']);
    return $conn;
}

$con = connect($config);        // You need to pass $config variable when calling function
if(!$con) die ('problem in connection');
Apul Gupta
  • 3,023
  • 3
  • 21
  • 30
0

I like to suggest the below code. Instead of array values, I would define variables in config.php and use it functions.php

config.php

<?php 
     define("DB_HOST", "localhost");
     define("DB_USERNAME", "root");
     define("DB_PASSWORD", "pass");
     define("DB_NAME", "sample");
?>

In functions.php

  include('config.php');
  $conn = mysql_connect(DB_HOST,DB_USERNAME,DB_PASSWORD);
Gunaseelan
  • 2,323
  • 5
  • 33
  • 40