简体   繁体   中英

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

I have Ubuntu 14.04 LTS. I set up apache, phpmyadmin and mysql. I can access databases through localhost/phpmyadmin using my set password and root as username. I have put a link inside /etc/apache2/sites-enabled that links to the original .conf file of the website located in /etc/apache2/sites-available. And it has these lines ( mypage.conf

php_value mysql.default.user    root
php_value mysql.default.password    mypass
php_value mysql.default.host    localhost

When I try to connect to database using this in my index.php it works prettily:

mysql_connect('localhost', 'root', 'mypass') or die(mysql_error());

But when I try to connect to database using this below:

mysql_connect(ini_get("mysql.default.host"), ini_get("mysql.default.user"), ini_get("mysql.default.password")) or die(mysql_error());

In return it posts this error message to the page and doesn't execute the rest of the code:

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

As I can understand from this, what it gets from default values are ''. So I must be doing something wrong about the .conf file. Can you help me about it?

As stated by @Vanitas, I changed the connection style to PDO instead of mysql. Here's my

connection.php

<?php
    DEFINE('DB_HOST', 'localhost');
    DEFINE('DB_NAME', 'mydb');
    DEFINE('DB_USER', 'usr');
    DEFINE('DB_PASS', 'pss');

    try{
        $db = new PDO('mysql:host='.DB_HOST.'; dbname='.DB_NAME, DB_USER, DB_PASS);
    }catch(PDOException $exeption){
        echo $exeption->getMessage(). '<br/>';
        die();
    }
?>

And I retrive it by using

require_once('../../0n/connection.php');

It's outside of the web directory. So, it's safe. I suppose. And it's working prettily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM