How to Configure MySql with PHP and Apache?
After installing PHP, Apache and MySql, let’s see whether everything works fine
Take a sample PHP-MySql program written in /usr/local/apache2/htdocs/mysql.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'check';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error in connecting to mysql');
$dbname = 'blog';
mysql_select_db($dbname);
echo "Using database";
$result = mysql_query("create table author (id integer not null )");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
If your mysql is configured well with php, you will be sucessfully able to execute the above script
<strong>Warning</strong>: mysql_connect() [<a href="http://localhost/function.mysql-connect">function.mysql-connect</a>]: Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2) in <strong>/usr/local/apache2/htdocs/mysql.php</strong> on line <strong>6</strong> Error connecting to mysql
This is because php is configured to work with the socket /var/mysql/mysql.sock. There are two ways by which we can solve this problem.
Way 1 (A Temporary Solution)
This is the simplest way to solve this. First find the mysql socket
$ mysql_config --socket /tmp/mysql.sock
Now check again the previous warning you got and what is the path of mysql.sock. In my case, if you check above, I got /var/mysql/mysql.sock
Now we have to create a symbolic link for the same
$ sudo mkdir /var/mysql $ sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
Now execute the mysql.php file. And you will find the script works fine.
Note: This is a temporary solution. This is because, every time you shut down the system or restart, a new socket is created. So you have to run the above command (creating symbolic link) every time you start the system or restart mysql.
Way 2
The second way is to change your php settings.
$ sudo /usr/local/apache2/bin/apachectl stop
Find php.ini
$ sudo find / -iname "*php.ini*" /etc/php.ini
Now get the value of mysql socket value
$ mysql_config --socket /tmp/mysql.sock
Now you may get different values. Edit /etc/php.ini. Substitute the above value you got in mysql.default_sock
mysql.default_socket = /tmp/mysql.sock
Now start apache
sudo /usr/local/apache2/bin/apachectl start
Now execute the mysql.php file. You will be able to execute it
Comments: