0

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?

kittenparry
  • 149
  • 1
  • 3
  • 11
  • 1
    Please read [this answer](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php?answertab=votes#tab-top), as you should really avoid using **mysql_** or **mysqli_**. Instead please refer to [PDO](http://php.net/manual/en/book.pdo.php) – Vanitas Jul 17 '15 at 12:37
  • @Vanitas I'll edit my code accordingly. Thank you for the information. – kittenparry Jul 17 '15 at 12:42
  • I guess it's better to keep configuration of MySQL connection in PHP scripts (or some configuration file) - this is very webserver depended, you need to have properly configured Apache, when you move to other server you will need to reconfigure it etc. – Ondřej Šotek Jul 17 '15 at 12:50
  • It's mysql.default_host , mysql.default_password and mysql.default_host according to http://php.net/manual/en/mysql.configuration.php#ini.mysql.default-host and use $host=ini_get("mysql.default_host") for better usage. – Golden_flash Sep 06 '15 at 15:12
  • @Vanitas thanks. I edited my code accordingly, you can check it in my answer. Glad to be the part of the future. – kittenparry Sep 06 '15 at 17:22

1 Answers1

0

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.

kittenparry
  • 149
  • 1
  • 3
  • 11