Hi there,
I'm trying to setup a website with a database. I want my php code to create the database and then input the data into it, however a get the error on my register page:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user '*****' (using password: YES) in /fg_membersite.php on line 479

Database Login failed! Please make sure that the DB login credentials provided are correct

i've been sitting in front of the computer for the day searching for an answer, so I've finally come to putting up this long code in the hope that someone would be kind enough to shed some light on my situation.

membersiteconfig.php

<?PHP
include'fg_membersite.php';

$fgmembersite = new FGMembersite();

//Provide your site name here
$fgmembersite->SetWebsiteName('');

//Provide the email address where you want to get notifications
$fgmembersite->SetAdminEmail('****@hotmail.com');

//Provide your database login details here:
//hostname, user name, password, database name and table name
//note that the script will create the table (for example, fgusers in this case)
//by itself on submitting register.php for the first time

$fgmembersite->InitDB(/*hostname*/'******.net',
/*username*/'L0v3ll',
/*password*/'sam0531',
/*database name*/'members',
/*table name*/'join');


//For better security. Get a random string from this link: http://tinyurl.com/randstr
// and put it here
$fgmembersite->SetRandomKey('qSRcVS6DrTzrPvr');

?>

fg_membersite.php

<?PHP

include 'class.phpmailer.php';
include 'formvalidator.php';

class FGMembersite
{
var $admin_email;
var $from_address;

var $username;
var $pwd;
var $database;
var $tablename;
var $connection;
var $rand_key;

var $error_message;

//-----Initialization -------
function FGMembersite()
{
$this->sitename = '*****';
$this->rand_key = '0iQx5oBk66oVZep';
}

function InitDB($host,$uname,$pwd,$database,$tablename)
{
$this->db_host = $host;
$this->username = $uname;
$this->pwd = $pwd;
$this->database = $database;
$this->tablename = $tablename;

}
function SetAdminEmail($email)
{
$this->admin_email = $email;
}

function SetWebsiteName($sitename)
{
$this->sitename = $sitename;
}

function SetRandomKey($key)
{
$this->rand_key = $key;
}

//-------Main Operations ----------------------
function RegisterUser()
{
if(!isset($_POST['submitted']))
{
return false;
}

$formvars = array();

if(!$this->ValidateRegistrationSubmission())
{
return false;
}

$this->CollectRegistrationSubmission($formvars);

if(!$this->SaveToDatabase($formvars))
{
return false;
}

if(!$this->SendUserConfirmationEmail($formvars))
{
return false;
}

$this->SendAdminIntimationEmail($formvars);

return true;
}

function ConfirmUser()
{
if(empty($_GET['code'])||strlen($_GET['code'])<=10)
{
$this->HandleError("Please provide the confirm code");
return false;
}
$user_rec = array();
if(!$this->UpdateDBRecForConfirmation($user_rec))
{
return false;
}

$this->SendUserWelcomeEmail($user_rec);

$this->SendAdminIntimationOnRegComplete($user_rec);

return true;
}

function Login()
{
if(empty($_POST['username']))
{
$this->HandleError("UserName is empty!");
return false;
}

if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}

$username = trim($_POST['username']);
$password = trim($_POST['password']);

if(!$this->CheckLoginInDB($username,$password))
{
return false;
}

session_start();

$_SESSION[$this->GetLoginSessionVar()] = $username;

return true;
}

function CheckLogin()
{
session_start();

$sessionvar = $this->GetLoginSessionVar();

if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}

function LogOut()
{
session_start();

$sessionvar = $this->GetLoginSessionVar();

$_SESSION[$sessionvar]=NULL;

unset($_SESSION[$sessionvar]);
}

//-------Public Helper functions -------------
function GetSelfScript()
{
return htmlentities($_SERVER['PHP_SELF']);
}

function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlentities($_POST[$value_name]);
}

function RedirectToURL($url)
{
header("Location: $url");
exit;
}

function GetSpamTrapInputName()
{
return 'sp'.md5('KHGdnbvsgst'.$this->rand_key);
}

function GetErrorMessage()
{
if(empty($this->error_message))
{
return '';
}
$errormsg = nl2br(htmlentities($this->error_message));
return $errormsg;
}
//-------Private Helper functions-----------

function HandleError($err)
{
$this->error_message .= $err."\r\n";
}

function HandleDBError($err)
{
$this->HandleError($err."\r\n mysqlerror:".mysql_error());
}

function GetFromAddress()
{
if(!empty($this->from_address))
{
return $this->from_address;
}

$host = $_SERVER['SERVER_NAME'];

$from ="nobody@$host";
return $from;
}

function GetLoginSessionVar()
{
$retvar = md5($this->rand_key);
$retvar = 'usr_'.substr($retvar,0,10);
return $retvar;
}

function CheckLoginInDB($username,$password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$username = $this->SanitizeForSQL($username);
$pwdmd5 = md5($password);
$qry = "Select name, email from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";

$result = mysql_query($qry,$this->connection);

if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. The username or password does not match");
return false;
}
return true;
}

function UpdateDBRecForConfirmation(&$user_rec)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$confirmcode = $this->SanitizeForSQL($_GET['code']);

$result = mysql_query("Select name, email from $this->tablename where confirmcode='$confirmcode'",$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Wrong confirm code.");
return false;
}
$row = mysql_fetch_assoc($result);
$user_rec['name'] = $row['name'];
$user_rec['email']= $row['email'];

$qry = "Update $this->tablename Set confirmcode='y' Where confirmcode='$confirmcode'";

if(!mysql_query( $qry ,$this->connection))
{
$this->HandleDBError("Error inserting data to the table\nquery:$qry");
return false;
}
return true;
}

function SendUserWelcomeEmail(&$user_rec)
{
$mailer = new PHPMailer();

$mailer->CharSet = 'utf-8';

$mailer->AddAddress($user_rec['email'],$user_rec['name']);

$mailer->Subject = "Welcome to ".$this->sitename;

$mailer->From = $this->GetFromAddress();

$mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
"Welcome! Your registration with ".$this->sitename." is completed.\r\n".
"\r\n".
"Regards,\r\n".
"Webmaster\r\n".
$this->sitename;

if(!$mailer->Send())
{
$this->HandleError("Failed sending user welcome email.");
return false;
}
return true;
}

function SendAdminIntimationOnRegComplete(&$user_rec)
{
if(empty($this->admin_email))
{
return false;
}
$mailer = new PHPMailer();

$mailer->CharSet = 'utf-8';

$mailer->AddAddress($this->admin_email);

$mailer->Subject = "Registration Completed: ".$user_rec['name'];

$mailer->From = $this->GetFromAddress();

$mailer->Body ="A new user registered at ".$this->sitename."\r\n".
"Name: ".$user_rec['name']."\r\n".
"Email address: ".$user_rec['email']."\r\n";

if(!$mailer->Send())
{
return false;
}
return true;
}

function ValidateRegistrationSubmission()
{
//This is a hidden input field. Humans won't fill this field.
if(!empty($_POST[$this->GetSpamTrapInputName()]) )
{
//The proper error is not given intentionally
$this->HandleError("Automated submission prevention: case 2 failed");
return false;
}

$validator = new FormValidator();
$validator->addValidation("name","req","Please fill in Name");
$validator->addValidation("email","email","The input for Email should be a valid email value");
$validator->addValidation("email","req","Please fill in Email");
$validator->addValidation("username","req","Please fill in UserName");
$validator->addValidation("password","req","Please fill in Password");


if(!$validator->ValidateForm())
{
$error='';
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
$error .= $inpname.':'.$inp_err."\n";
}
$this->HandleError($error);
return false;
}
return true;
}

function CollectRegistrationSubmission(&$formvars)
{
$formvars['name'] = $this->Sanitize($_POST['name']);
$formvars['email'] = $this->Sanitize($_POST['email']);
$formvars['username'] = $this->Sanitize($_POST['username']);
$formvars['password'] = $this->Sanitize($_POST['password']);
}

function SendUserConfirmationEmail(&$formvars)
{
$mailer = new PHPMailer();

$mailer->CharSet = 'utf-8';

$mailer->AddAddress($formvars['email'],$formvars['name']);

$mailer->Subject = "Your registration with ".$this->sitename;

$mailer->From = $this->GetFromAddress();

$confirmcode = $formvars['confirmcode'];

$confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;

$mailer->Body ="Hello ".$formvars['name']."\r\n\r\n".
"Thanks for your registration with ".$this->sitename."\r\n".
"Please click the link below to confirm your registration.\r\n".
"$confirm_url\r\n".
"\r\n".
"Regards,\r\n".
"Webmaster\r\n".
$this->sitename;

if(!$mailer->Send())
{
$this->HandleError("Failed sending registration confirmation email.");
return false;
}
return true;
}
function GetAbsoluteURLFolder()
{
$scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
$scriptFolder .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
return $scriptFolder;
}

function SendAdminIntimationEmail(&$formvars)
{
if(empty($this->admin_email))
{
return false;
}
$mailer = new PHPMailer();

$mailer->CharSet = 'utf-8';

$mailer->AddAddress($this->admin_email);

$mailer->Subject = "New registration: ".$formvars['name'];

$mailer->From = $this->GetFromAddress();

$mailer->Body ="A new user registered at ".$this->sitename."\r\n".
"Name: ".$formvars['name']."\r\n".
"Email address: ".$formvars['email']."\r\n".
"UserName: ".$formvars['username'];

if(!$mailer->Send())
{
return false;
}
return true;
}

function SaveToDatabase(&$formvars)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
if(!$this->Ensuretable())
{
return false;
}
if(!$this->IsFieldUnique($formvars,'email'))
{
$this->HandleError("This email is already registered");
return false;
}

if(!$this->IsFieldUnique($formvars,'username'))
{
$this->HandleError("This UserName is already used. Please try another username");
return false;
}
if(!$this->InsertIntoDB($formvars))
{
$this->HandleError("Inserting to Database failed!");
return false;
}
return true;
}

function IsFieldUnique($formvars,$fieldname)
{
$field_val = $this->SanitizeForSQL($formvars[$fieldname]);
$qry = "select username from $this->tablename where $fieldname='".$field_val."'";
$result = mysql_query($qry,$this->connection);
if($result && mysql_num_rows($result) > 0)
{
return false;
}
return true;
}

function DBLogin()
{

$this->connection = mysql_connect($this->db_host,$this->username,$this->pwd);

if(!$this->connection)
{
$this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct");
return false;
}
if(!mysql_select_db($this->database, $this->connection))
{
$this->HandleDBError('Failed to select database: '.$this->database.' Please make sure that the database name provided is correct');
return false;
}
if(!mysql_query("SET NAMES 'UTF8'",$this->connection))
{
$this->HandleDBError('Error setting utf8 encoding');
return false;
}
return true;
}

function Ensuretable()
{
$result = mysql_query("SHOW COLUMNS FROM $this->tablename");
if(!$result || mysql_num_rows($result) <= 0)
{
return $this->CreateTable();
}
return true;
}

function CreateTable()
{
$qry = "Create Table $this->tablename (".
"id_user INT NOT NULL AUTO_INCREMENT ,".
"name VARCHAR( 128 ) NOT NULL ,".
"email VARCHAR( 64 ) NOT NULL ,".
"phone_number VARCHAR( 16 ) NOT NULL ,".
"username VARCHAR( 16 ) NOT NULL ,".
"password VARCHAR( 32 ) NOT NULL ,".
"confirmcode VARCHAR(32) ,".
"PRIMARY KEY ( id_user )".
")";

if(!mysql_query($qry,$this->connection))
{
$this->HandleDBError("Error creating the table \nquery was\n $qry");
return false;
}
return true;
}

function InsertIntoDB(&$formvars)
{

$confirmcode = $this->MakeConfirmationMd5($formvars['email']);

$formvars['confirmcode'] = $confirmcode;

$insert_query = 'insert into '.$this->tablename.'(
name,
email,
username,
password,
confirmcode
)
values
(
"' . $this->SanitizeForSQL($formvars['name']) . '",
"' . $this->SanitizeForSQL($formvars['email']) . '",
"' . $this->SanitizeForSQL($formvars['username']) . '",
"' . md5($formvars['password']) . '",
"' . $confirmcode . '"
)';
if(!mysql_query( $insert_query ,$this->connection))
{
$this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
return false;
}
return true;
}
function MakeConfirmationMd5($email)
{
$randno1 = rand();
$randno2 = rand();
return md5($email.$this->rand_key.$randno1.''.$randno2);
}
function SanitizeForSQL($str)
{
if( function_exists( "mysql_real_escape_string" ) )
{
$ret_str = mysql_real_escape_string( $str );
}
else
{
$ret_str = addslashes( $str );
}
return $ret_str;
}

/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);

if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}

return $str;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
}
?>

register.php

<?PHP
include "membersiteconfig.php";

if(isset($_POST['submitted']))
{
if($fgmembersite->RegisterUser())
{
$fgmembersite->RedirectToURL("thank-you.html");
}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Contact us</title>
<link rel="STYLESHEET" type="text/css" href="style/fg_membersite.css" />
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<link rel="STYLESHEET" type="text/css" href="style/pwdwidget.css" />
<script src="scripts/pwdwidget.js" type="text/javascript"></script>
</head>
<body>

<!-- Form Code Start -->
<div id='fg_membersite'>
<form id='register' action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Register</legend>

<input type='hidden' name='submitted' id='submitted' value='1'/>

<div class='short_explanation'>* required fields</div>
<input type='text' class='spmhidip' name='<?php echo $fgmembersite->GetSpamTrapInputName(); ?>' />

<div><span class='error'><?php echo $fgmembersite->GetErrorMessage(); ?></span></div>
<div class='container'>
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' value='<?php echo $fgmembersite->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='register_name_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' value='<?php echo $fgmembersite->SafeDisplay('email') ?>' maxlength="50" /><br/>
<span id='register_email_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='username' >UserName*:</label><br/>
<input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username') ?>' maxlength="50" /><br/>
<span id='register_username_errorloc' class='error'></span>
</div>
<div class='container' style='height:80px;'>
<label for='password' >Password*:</label><br/>
<div class='pwdwidgetdiv' id='thepwddiv' ></div>
<!-- <noscript> -->
<input type='password' name='password' id='password' maxlength="50" />
<!-- </noscript> -->
<div id='register_password_errorloc' class='error' style='clear:both'></div>
</div>

<div class='container'>
<input type='submit' name='Submit' value='Submit' />
</div>

</fieldset>
</form>
<!-- client-side Form Validations:
Uses the excellent form validation script from JavaScript-coder.com-->

<script type='text/javascript'>
// <![CDATA[
var pwdwidget = new PasswordWidget('thepwddiv','password');
pwdwidget.MakePWDWidget();

var frmvalidator = new Validator("register");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");

frmvalidator.addValidation("email","req","Please provide your email address");

frmvalidator.addValidation("email","email","Please provide a valid email address");

frmvalidator.addValidation("username","req","Please provide a username");

frmvalidator.addValidation("password","req","Please provide a password");

// ]]>
</script>
<div id='fg_crdiv'><p><a href='http://www.html-form-guide.com'
>HTML form guide - email forms, registration forms, form generators and more</a>.</p></div>
</div>
<!--
Form Code End (see html-form-guide.com for more info.)
-->

</body>
</html>

any thoughts would be really appreciated.
Thanks

Recommended Answers

All 9 Replies

Hello, I gave it a really short glimpse but I'm missing the declaration

var $db_host;

you're using $this->db_host, but it is never declared.

Also, are you sure that your hostname ends in .net? It could be, of course, but normally it's just localhost. And, do you need to use this class? There are really strange functions in it. Take a look at mysqli, for example.

Replace this much code and check whether all three values are coming correct or not.
If its correct that means code is right and problem is in mysql credentials.

function DBLogin()
{
echo '--host--'.$this->db_host.'--username--'.$this->username.'--pwd--'.$this->pwd;
$this->connection = mysql_connect($this->db_host,$this->username,$this->pwd);
Member Avatar for diafol

Ok, first off, is this your code? Be honest. If not, seek out the *genius* who wrote it.

the var "pwd" is being used for both the password of the user during registration as well as password for the database. Hope this helps, my 2¢.

Hi guys,
Thanks for looking through the code and helping out. Ardev, it's not entirely my code. I got most of it when browsing the web and came across a share website, I've also gotten help elsewhere. Didn't think this was a crime when they say free to use.

vibhadevit, I get an echo back with my details, then the error

"Warning: mysql_connect() [function.mysql-connect]: Access denied for user in fg_membersite.php on line 480"

Can you use your login credentials in below code and post output.
Because i think there is something wrong in credentials only.

<?php

$db_host = "localhost";
$db_user = "root";
$db_password = "";
$db_database = "db_name"

$link = mysql_connect($db_host, $db_user, $db_password);
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db($db_database, $link);
if (!$db_selected) {
    die ('Db selection error : ' . mysql_error());
}

?>
commented: great help +1

Finally it's working,

Thanks entirely to the help of vibhadevit.

Member Avatar for diafol

Maybe give him some rep?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.