Connect PHP to mysql server running on Mac [duplicate] - php

This question already has answers here:
Warning: mysqli_connect(): (HY000/2002): No such file or directory
(6 answers)
Closed 2 years ago.
I am trying to connect to my MySQL server on a mac using PHP after starting the server using brew services start mysql After this I can see that the MySQL server has successfully started. However, when I try to access my webpage using:
<?php
/* Attempt to connect to MySQL database */
$link = mysqli_connect('localhost', 'root', 'password', 'databasename');
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
The webpage start spinning continuously and doesn't load. I was wondering what's the issue as I can log into the root from the command line as well as see the tables. And the bre shows MySQL server running in the background.
EDIT I managed to print my error however, now I get an error:
Warning: mysqli_connect(): (HY000/2002): No such file or directory However, homebrew shows my MySQL server running.

Try to change your host from localhost to 127.0.0.1
$link = mysqli_connect('127.0.0.1', 'root', 'password', 'databasename');

You better make sure if mysqli extension is available in php.ini
(If it is not enabled, go into the php.ini file and remove ; from the mysqli line.)
If mysqlit is enabled, try running the code below and restart the server/terminal php task if anything changes
cd /var mkdir mysql cd mysql ln -s /tmp/mysql.sock mysql.sock
Check your credentials you give into the mysqli_connect
If everything is okay, and you cant still connect try installing helpful programs like MAMP. They will create an Apache Server with Php and MySql server on local computer without a problem with full configuration

Related

"Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused" after updating a PHP file [duplicate]

I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I have been using postman to test to see if the connection is working, but I keep receiving this error message:
Connection failed: SQLSTATE[HY000] [2002] Connection refused
Before I was receiving an error message of:
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.
Any help regarding this would be appreciated.
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get
the process id (pid), simulate a failure by killing the "mysql"
process and verify its status as running with new process id after
sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl
I spent quite a few hours in a docker environment where all my containers are docker containers and I was using Phinx for migrations. Just to share different responses with different configurations.
Working solutions
"host" => "db", // {docker container's name} Worked
"host" => "172.22.112.1", // {some docker IP through ipconfig - may change on every instance - usually something like 172.x.x.x} Worked
Non-working solutions
"host" => "127.0.0.1", // SQLSTATE[HY000] [2002] Connection refused
"host" => "docker.host.internal", // SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name does not resolve
"host" => "localhost", // SQLSTATE[HY000] [2002] No such file or directory
I was running Phinx in following way.
docker compose --env-file .env run --rm phinx status -e development
Using MAMP I changed the host=localhost to host=127.0.0.1. But a new issue came "connection refused"
Solved this by putting 'port' => '8889', in 'Datasources' => [
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
1. server cert verify flag
I was required to use SSL to connect, and needed to set PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT to false in the new PDO options array, besides the entry PDO::MYSQL_ATTR_SSL_CA for the CA file.
Without it, the mysql log on the server helpfully mentions
2021-07-27 17:02:51 597605 [Warning] Aborted connection 597605 to db: 'unconnected' user: 'unauthenticated' host: '192.168.10.123' (This connection closed normally without authentication)
where I was definitely passing the right db and username and such in the DSN. An empty options array will show the db and user in the error log, at least. I am sure there is a valid, technical reason for these things.
I am adding this information so I can more easily find it, the next time I end up on this page..
2. host in connection string
In the context of SSL, I've also seen the error when using the IP address instead of the hostname to connect, if the hostname was used as CN (Common Name) in the certificate.
For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:
/Applications/mampstack-7.1.21-0/php/bin
In terminal run vim ~/.bash_profile to open ~/.bash_profile
Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:
export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"
Hit ESC, Type :wq, and hit Enter
In Terminal run source ~/.bash_profile
In Terminal type which php, output should be the path to MAMP PHP install.
I had the same issue on a docker container from php:8.0-fpm-alpine image. I just added the following line in the Dockerfile and it fixed the issue:
RUN apk add mysql-client
I had a similar problem once, turned out the User in the database was created with something like:
CREATE USER 'webpage'#'localhost' IDENTIFIED BY 'password';
worked fine when the connection details php script had localhost, but not when the IP address was there. A quick swap (ip address when creating user and localhost in connection details) revealed those two things have to match.
For everyone if you still strugle with Refusing connection, here is my advice. Download XAMPP or other similar sw and just start MySQL. You dont have to run apache or other things just the MySQL.

Docker php8.1 cant connect to MySQL [duplicate]

I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I have been using postman to test to see if the connection is working, but I keep receiving this error message:
Connection failed: SQLSTATE[HY000] [2002] Connection refused
Before I was receiving an error message of:
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.
Any help regarding this would be appreciated.
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get
the process id (pid), simulate a failure by killing the "mysql"
process and verify its status as running with new process id after
sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl
I spent quite a few hours in a docker environment where all my containers are docker containers and I was using Phinx for migrations. Just to share different responses with different configurations.
Working solutions
"host" => "db", // {docker container's name} Worked
"host" => "172.22.112.1", // {some docker IP through ipconfig - may change on every instance - usually something like 172.x.x.x} Worked
Non-working solutions
"host" => "127.0.0.1", // SQLSTATE[HY000] [2002] Connection refused
"host" => "docker.host.internal", // SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name does not resolve
"host" => "localhost", // SQLSTATE[HY000] [2002] No such file or directory
I was running Phinx in following way.
docker compose --env-file .env run --rm phinx status -e development
Using MAMP I changed the host=localhost to host=127.0.0.1. But a new issue came "connection refused"
Solved this by putting 'port' => '8889', in 'Datasources' => [
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
1. server cert verify flag
I was required to use SSL to connect, and needed to set PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT to false in the new PDO options array, besides the entry PDO::MYSQL_ATTR_SSL_CA for the CA file.
Without it, the mysql log on the server helpfully mentions
2021-07-27 17:02:51 597605 [Warning] Aborted connection 597605 to db: 'unconnected' user: 'unauthenticated' host: '192.168.10.123' (This connection closed normally without authentication)
where I was definitely passing the right db and username and such in the DSN. An empty options array will show the db and user in the error log, at least. I am sure there is a valid, technical reason for these things.
I am adding this information so I can more easily find it, the next time I end up on this page..
2. host in connection string
In the context of SSL, I've also seen the error when using the IP address instead of the hostname to connect, if the hostname was used as CN (Common Name) in the certificate.
For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:
/Applications/mampstack-7.1.21-0/php/bin
In terminal run vim ~/.bash_profile to open ~/.bash_profile
Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:
export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"
Hit ESC, Type :wq, and hit Enter
In Terminal run source ~/.bash_profile
In Terminal type which php, output should be the path to MAMP PHP install.
I had the same issue on a docker container from php:8.0-fpm-alpine image. I just added the following line in the Dockerfile and it fixed the issue:
RUN apk add mysql-client
I had a similar problem once, turned out the User in the database was created with something like:
CREATE USER 'webpage'#'localhost' IDENTIFIED BY 'password';
worked fine when the connection details php script had localhost, but not when the IP address was there. A quick swap (ip address when creating user and localhost in connection details) revealed those two things have to match.
For everyone if you still strugle with Refusing connection, here is my advice. Download XAMPP or other similar sw and just start MySQL. You dont have to run apache or other things just the MySQL.

MySQL Wordpress Nginx dnsmasq: Error: Error establishing a database connection

I'm trying to get a local development environment set up. I can't get wordpress to connect to mysql. I can duplicate the error with the following command:
wp core install --url=http://uganda.localhost/ --title="Uganda Aid" --admin_user="Jack" --admin_password="thepassword" --admin_email="JackWinterstein#msf.org"
Result:
Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or we can’t contact the database server at `localhost`. This could mean your host’s database server is down.
Things I tried:
Looked in wp-config and made sure the database name and credentials were correct. I can connect via cli
Updated homebrew.mxcl.mysql.plist to include --bind-address=*
Looked at the mysql socket location: mysql_config --socket producef /tmp/mysql.sock
Updated php.ini to reflect the attached below
Updated my.cnf to reflect bind-address = *
I am using dnsmasq (as shown in https://medium.com/#charlesthk/wordpress-on-os-x-with-nginx-php-mysql-62767a62efc4)
Environment
Darwin osx10.14, mysql Ver 8.0.17, nginx version: nginx/1.17.3, Wordpress 5.2.2, PHP 7.3.9
I figured it out. The problem was that caching_sha2_password authentication method unknown to the client. To fix this I ran:
ALTER USER jack#localhost IDENTIFIED WITH mysql_native_password BY 'thepassword';
I found this by: creating a basic test script:
<?php
$link = mysqli_connect('localhost', 'jack', 'thepassword');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);
?>
And the resulting error mentioned the caching_sha2_password authentication method.

How to configure XAMPP to connect to MySQL remotely

I have a problem to connect my online MySQL database from my local system.
I installed XAMPP on my Windows 7 and created a PHP file with this code:
<?php
$db_path = mysqli_connect('printcity24.com', 'printci1_admin', 'xr10s20191', 'printci1_db', '3306');
if(!$db_path) {
echo mysqli_connect_error();
}else{
echo "Connected successfully";
}
?>
Then i created a database on my website : www.printcity24.com
My web host admin configured my host and opened firewall.
When i use XAMPP command line to connect to my database every thing is ok, i can connect to my database remotely with this code :
# mysql -u printci1_admin -p -h printcity24.com
but when i use php code to connect to my database i get this error :
Warning: mysqli_connect(): MySQL server has gone away in D:\Xampp Server\htdocs\st\index.php on line 2
Warning: mysqli_connect(): (HY000/2006): MySQL server has gone away in D:\Xampp Server\htdocs\st\index.php on line 2
MySQL server has gone away
I upload my php code on to other websites and test for connection and everything is "ok" but on my local xampp can't connect.
In this link said i have to use this command :
setsebool -P httpd_can_network_connect=1
but I don't know where to put this code and how to configure my xampp.

PHP not able to connect to MySQL in Ubuntu based custom S2I image

Playing with Openshift origin 3.9 on my custom servers. So far it has been a pleasant experience. I've been building a custom s2i image based on Ubuntu for my LEMP stack.
I'm not able to connect to the MySQL database. I always get an error saying:
Failed to connect to MySQL: (2002) No such file or directory
Here's my PHP code:
$mysql_database = getenv("MYSQL_DATABASE");
$mysql_server_name =getenv("MYSQL_HOST");
$mysql_username = getenv("MYSQL_USER");
$mysql_password = getenv("MYSQL_PASSWORD");
$mysql_port = getenv("MYSQL_PORT");
$mysqli = new mysqli($mysql_server_name, $mysql_username, $mysql_password, $mysql_database, $mysql_port);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
die();
}
Some observations:
I'm able to connect from MySQL CLI client from inside the pod.
The same app/code works fine with the official openshift PHP s2i image.
Am I missing anything in my s2i?
Check your phpinfo() and search for MySQLi extension. If you can't find, that means you do not have the extension installed yet and it needs to install.
try installing from terminal
(Ubuntu/Mint) $ sudo apt-get install php(version)-mysql
replace (version) with any of your php version number. For example, php7.0 / php7.1, etc.
To check phpinfo(), create a phpinfo.php file which you can access from url with the content
<?php
phpinfo()
If you have everything and still unable to connect? Try checking your mysql.sock file path.
Open the php.ini file and find this line:
mysql.default_socket
And make it (know where your mysql.sock located)
mysql.default_socket = /path/to/mysql.sock

Categories