Alex Coplan Alex Coplan - 1 year ago 72
MySQL Question

mysql connect - should username/password be hardcoded?

I'm an iPhone developer, and I've just started out with PHP & mysql (making websites for others, and web services for my apps).

Whenever I hardcoded my username and password into a PHP file to connect to the database I felt a bit odd. Example:

$con = mysql_connect('localhost:8888','root','password');

I find this slightly awkward if I ever have to show code to anybody.

  • Is this secure or good practice?

  • Is there another way I should be connecting to the database?

I would be very grateful for any advice related to this issue.

Answer Source

For scripts that are going to be redistributed it would be better to group these together and either have them as constants or variables.


define('DBHOST', 'localhost');
define('DBPORT', '8080');
define('DBNAME', 'my_db_name');
define('DBUSER', 'root');
define('DBPASS', 'password');


$con = mysql_connect(DBHOST.':'. DBPORT,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);

Doing this will make it easier for someone to make changes in the future instead of having to trawl through code to find where any connections are made etc.

For slightly better security the config.php script could be placed outside of the doc root so that it cannot be called directly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download