Jump to content

Simple Question -> Connecting to MySQL Database


Raider

Recommended Posts

Hi!

 

It's been a while since I've programmed in PHP / MySQL, so please bear with me.

 

I'm having problems connecting to my MySQL database (which has been created and all, using PhpMyAdmin). Here's the code:

 

globalvariables.php

$cfg["db"]["name"] = "fabiansat_info";
$cfg["db"]["username"] = "fabiansat_u";
$cfg["db"]["password"]  = "aaaa";
$cfg["db"]["host"]  = "localhost";

 

includes/database.php

function connect_db() {
$conn = mysql_connect($cfg["db"]["host"], $cfg["db"]["username"], $cfg["db"]["password"]) or die
	(mysql_error());		

if ($conn) echo "Connection successful!";			

mysql_select_db($cfg["db"]["name"]);
}

 

test.php

include('globalvariables.php');
include('includes/database.php');

connect_db();

 

 

The error I get is the following:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'vhostswww'@'localhost' (using password: NO) in /www/vndv.com/f/a/b/fabiansat/htdocs/includes/database.php on line 28
Access denied for user 'vhostswww'@'localhost' (using password: NO)

 

If I change the $cfg["db"]["host"], etc. part in the connect_db() funciton and explicitly state write the username, password, host, etc. it works fine.  :confused:

 

Thanks :)

The $cfg array with connection settings is not global.... This array is outside the scope of function connect_db().

 

connect_db() can't "see" this array... when you try to run this function, it tries to connect with the web user (in your case, vhostswww) without password.

 

The only way for your code to work is declaring $cfg as global inside the function connect_db (a bad practice anyway...):

 

function connect_db() {
   global $cfg;
   $conn = mysql_connect($cfg["db"]["host"], $cfg["db"]["username"], $cfg["db"]["password"]) or die
      (mysql_error());      

   if ($conn) echo "Connection successful!";         

   mysql_select_db($cfg["db"]["name"]);
}

You need to pass the values as parameters when you call the function. Edit: Which is the way that you did it, good.

 

By using the global keyword in the function definition you break the general purpose nature of the function. That function can only connect the way it was hard-coded to do and you might as well not be using a function at all.

 

By passing the parameters in the function call (and returning the connection link), you could reuse that function if you needed to connect to multiple database servers at the same time.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.