Search code examples
mysqldatabasemysql-real-escape-string

mysql_real_escape_string error


I'm getting Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'username'@'localhost' (using password: NO)

Here's my code..

<?php
include 'config.php';
$email = mysql_real_escape_string($_GET['email']);

$validation = filter_var($email, FILTER_VALIDATE_EMAIL);
if ( $validation ) {
    // Make a MySQL Connection
    mysql_connect($Host,$Username,$Password) or die(mysql_error());
    mysql_select_db($Database) or die(mysql_error());

    // Insert rows
    mysql_query("INSERT INTO formusers
    (formemail) VALUES('$email') ") 
    or die(mysql_error()); 
}
?>

It does work if I move the lines to make a database connection up. Is it necessary to make a database connection before using mysql_real_escape_string or am I just doing it wrong?


Solution

  • Yes, you do need an open mysql connection in order to do that.

    I recommend you put the mysql_connect() on top of the script to make sure this error will never occur. (of course, it can still happen if you connect wrongly to the database)