tags:

views:

27

answers:

4

Hello,

I am using this script to read a value in a session, then I want to query the database about this value :

    <?php
session_start();
$user_id = $_SESSION["user_id"] ;
echo "Your user_id is: $user_id \n" ;

$query = sprintf("SELECT * FROM `customers` WHERE id='%s' ", $user_id);
$result = mysql_query($query);

if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

while ($row = mysql_fetch_assoc($result)) {
    $email =  $row['email'] . "\n";
    echo "Your e-mail adress is : $email \n" ;
}
?>

I get this when I test the page with my browser: Your user_id is: 1430

Invalid query: Access denied for user 'nobody'@'localhost' (using password: NO) Whole query: SELECT * FROM customers WHERE id='1430'

Thanks a lot!

+1  A: 

The username nobody needs a password to use the database. The error clearly states this. The user nobody for the server localhost has its access denied when using no password

Access denied for user 'nobody'@'localhost' (using password: NO)

OR, although this is unlike, the machine you are running your code from does not have access to the machine that it running the database.

jakenoble
+1  A: 

I'm fairly sure your id is an INTEGER, so the following should work:

$query = sprintf("SELECT * FROM `customers` WHERE id=%d ", $user_id);

There also seems to be a problem with authenticating against the database. Have you successfully connected to the database using mysql_connect()?

halfdan
This isn't the case, because the query is being built correctly, you can see this from the error `SELECT * FROM customers WHERE id='1430' `
jakenoble
I didn't say it's build incorrectly. I just say that the id='whatever' will fail, because he's comparing INTEGER with CHAR/TEXT.
halfdan
+4  A: 

Connect to your database server first and select a database using mysql_connect and mysql_select_db. The mysql_query function will try to open a connection with default parameters, or as the manual puts it:

If no such link is found, it will try to create one as if mysql_connect() was called with no arguments.

Hence, PHP is trying to connect to localhost with username "nobody" and no password.

mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('my_database');

..and you're ready to go.

Tatu Ulmanen
+1  A: 

You need to connect to the database host with a valid user/password before querying:

mysql_connect($mysqlHost, $mysqlUser, $mysqlPassword);

Then, you need to select the database:

mysql_select_db($mysqlDatabase) ;
Fanis