0

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?

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

Yes it is required.

Note:

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

http://php.net/manual/en/function.mysql-real-escape-string.php

Comments

1

If you can't establish a mysql connection you can use:

mysql_escape_string

BUT: It's DEPRECATED as of PHP 5.3.0!

Always use mysql_real_escape_string if possible!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.