PHP: Unknown MySQL server host with mysqli - php

I have the following code:
$username = 'username';
$password = 'password';
$host = 'localhost';
$db = 'dbname';
$dbh = new mysqli('p:'.$host, $username, $password, $db)
or die('no connection to server');
But I get the following error
PHP Warning: mysqli::mysqli() [<a href='function.mysqli-mysqli'>function.mysqli-mysqli</a>]: (HY000/2005): Unknown MySQL server host 'p:localhost' (1) in /var/www/vhosts/politiker.lu/httpdocs/includes/sql.php on line 8
This intrigues me because the very same code worked on my development environment. Now that I want to set it up on my production server, it does not work. Any ideas?
Note: I am not very good with servers, so excuse me if the error should be something trivial.
EDIT 1
Here are the versions:
Development PHP (5.3.3-1ubuntu9.1) + MySQL(5.1.49-1ubuntu8.1)
Production PHP (5.2.4-2ubuntu5.12) + MySQL(5.0.51a)

take out the p: like this:
$dbh = new mysqli($host, $username, $password, $db)
or die('no connection to server');

Just adding this since I didn't think it was clear, but the problem is definitely your production version of PHP. Persistent connections for the mysqli extensions weren't added until 5.3 since they caused headaches before.
Some hosts might have different versions of PHP installed... I realized today that I can make HostGator use PHP 5.3! I just had to add to my .htaccess file:
Action application/x-hg-php53 /cgi-sys/php53
AddType application/x-hg-php53 .php

i think you missed the mysqli package in this server. Try :
sudo apt-get install php5-mysqli
if apt-get says it is already installed try to do a ping to localhost, if don't resolve edit /etc/hosts and check the line where localhost points to 127.0.0.1
should be there, if not, your server its horribly configured!
do a
ifconfig
and check if you get some output like this...
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0

You need to specify the actual location of the MySQL server. For development, it is localhost (most likely), just how you have it configured. But for production servers, it is going to be something else. I doubt it should be localhost.

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.

MSSQL VIA FreeTDS, ODBC, and Cpanel Unknown host machine name (severity 2)

I have installed FreeTDS 0.91, ODBC, on a Cpanel server running Centos 6.5x64. Everything appears to be running fine and I can connect to the remote MSSQL 2012 server using:
/usr/local/freetds/bin/tsql -S sqlserver -U test -P mypassword
and succesfully execute queries in the database.
I can also connect through:
isql -v sqlserverdatasource test mypasswordhere
But for some reason /usr/local/freetds/bin/tsql -LH server.ip.here
returns no information or errors which doesn't make much sense when it is proven I can connect with the other methods above.
So now when running a test script from a cpanel account on the machine I get:
Unknown host machine name (severity 2)
Here is the test script:
//Database connection function.
function getConnection() {
try {
//$dbconnect = new PDO("sqlserver:Server=server.ip.here,1433;Database=dbname", "user", "password");
$dbconnect = new PDO("dblib:host=server.ip.here,1433;dbname=dbname", 'user', 'password');
} catch (PDOException $e) {
echo "CONNECTION ERROR.<br>Error message:<br><br>" . $e->getMessage();
die();
}
if (!$dbconnect) {
die('Cant connect to database. Please try again later!');
}
else{
echo "i'm in!";
return $dbconnect;
}
}
The first commented line is the old one using sqlserv which I found did not work at all from what i can tell because of the x64 OS. I have also tried with "" around user and pass as well as no marks at all.
php -m does show PDO and pdo-dblib.
Any ideas where I can look next?
Update: This was fixed. I missed in freetds.conf:
[global]
# TDS protocol version
tds version = 8.0
It was originally set to 4.5 instead of 8.
The fix for me was with three steps:
First, I edited /etc/freetds/freetds.conf and changed the tds version like this:
tds version = 8.0
The second step was not entering port number. The port was already 1433, and not specifying it fixed the exact same issue on my case.
Lastly, to connect properly, I had to restart networking as #user1054844 mentioned as this:
/etc/init.d/networking restart
After all these steps, I was able to connect and work with the SQL Server database.
You actually did not need ODBC at all since your connect script is using pdo_dblib not odbc. You can just install FreeTDS than enable pdo_dblib via the compile time flag in rawopts and rebuild via EasyApache. Of course cPanel specifics for this are a bit different.
I just did this for a friend and decided to document it since it is hard to find accurate clear information for FreeTds and pdo_dblib on cPanel.
Guide is here: FreeTDS And pDO_dblib On cPanel

Can not connect to SQL SERVER Using Latest Drivers for PHP

I have been trying to figure out which dll and how to use it to connect to sql server.
It was much easier using the old php_mssql.
I am using Xampp on WinXP Pro SP3. I have been unable to figure out how to connect, i have search the manual, and none of the command's work.
I get PDO Error Driver Not Found
extension-php_pdo_sqlsrv_54_ts.dll
extension=php_sqlsrv_54_ts.dll
I realized that I must use the SQLSERV 2.0 Drivers. But which dll is the correct one? And what syntax must I use to connect and run queries?
Thank you.
One way of doing this is using FreeTDS for Windows
I am assuming you have PHP >5.3
Download this http://download.moodle.org/download.php/dblib/php53/DBLIB_TS.zip
Add this line to your php.ini extension=php_dblib.dll
You will also need to make a file called freetds.conf in the root directory of your PHP installation.
It should look something like this:
[global]
host = xxx.xxx.xxx.xxx (host name or ip of the MSSQL server)
port = 1433
client charset = UTF-8
tds version = 8.0
text size = 20971520
Restart Apache and try running this script:
<?php
$link = mssql_connect('localhost', 'db_user', 'db_password');
if(!$link) {
echo'Could not connect';
die('Could not connect: ' . mssql_error());
}
echo'Successful connection';
mssql_close($link);
?>
hit me up on fb if this does not work ;)

"Can't connect to local MySQL server through socket" on linux server

I'm having a hard time getting my website connected to the mySQL database on host. However, when I was running my website on the PC by Apache it was connecting smoothly. The snippet I'm using to connect is:
<?php
$conn_error = 'Could not connect';
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_db = 'firstdatabase';
if(!mysql_connect($mysql_host,$mysql_user,$mysql_pass)|| !#mysql_select_db($mysql_db)){
die($conn_error);
}else{
//echo 'Connected';
}
?>
And it gives me the following error when I try to connect to mysql on the web host:
Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server
through socket 'MySQL' (2) in /home/umudo/public_html/connectserver.inc.php on line 10
I searched through the web for finding a solution but couldn't find any exact example of this.
Help: http://dev.mysql.com/doc/refman/5.0/en/connecting.html
Says:
On Unix, MySQL programs treat the host name localhost specially, in a
way that is likely different from what you expect compared to other
network-based programs. For connections to localhost, MySQL programs
attempt to connect to the local server by using a Unix socket file.
So you have to
use "127.0.0.1" instead of "localhost" to use tcpip instead of sockets, or
enable sockets in mysql server config (socket connections are probably disabled and that causes that error on linux)
Second method is better - using sockets for local connections is better than TCP/IP (better performance), but you may have no privileges to mysql configuration on that server.
Try installing phpmyadmin or php5-mysql as in apt-get install phpmyadmin.

Categories