14

I'm using POST method to insert some data to db on my server.This is my connection.php file that is stored in my http://www.url.com/public_html.

    <?php

$servername = "http://www.url.com";
$username = "db_username";
$password = "db_password";
$databaseName = "db_name";

$connect = new mysqli($servername,$username,$password,$databaseName);

if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
} 
echo "Connected successfully";

?>

This is insert.php file also stored in http://www.url.com/public_html that I use to insert data in database.

<?php

if($_SERVER["REQUEST_METHOD"]=="POST"){
    require'connection.php';
    createStudent();
}
function createStudent(){
    
    global $connect;
    
    $name = $_POST["name"];
    $lastname = $_POST["lastname"];
    $age = $_POST["age"];
    
    $query="INSERT INTO  `demo` (  `name` ,  `lastname` ,  `age` ) 
    VALUES ('$name','$lastname','$age')";
    mysqli_query($connect,$query)or die (mysqli_error($connect));
    mysqli_close($connect);
}
?>

I use postman, and my Android app to test this but I'm getting: Connection failed: php_network_getaddresses: getaddrinfo failed: Name or service not known error.

2
  • If your database is on the same machine, use $servername = "localhost". Commented Dec 14, 2015 at 12:04
  • 1
    It's because you can't resolve the host name Maybe DNS problems, host is unreachable...
    – Apb
    Commented Dec 14, 2015 at 12:06

5 Answers 5

23

My database is on the same machine so I just needed to edit:

$servername = "localhost"

Now everything is working just fine.

7

The value you've specified for $servername is not a host name but rather a URL, or resource name. The host name would be just www.url.com.

Of course, as you've already discovered, localhost is the correct host name if the client and server reside on the same box.

2

For people coming from Google: If you work with Docker, you might use the name of the database docker container here, like

$dbserver='mydockerbox-mysql';

if your docker-compose.yml looks like this:

services:
  mydockerbox-mysql:
    image: mysql:5.7.26
    container_name: mydockerbox-mysql
1
  • This solution worked for me. If you are using docker, just use the name of the database container_name and it should work just fine. Commented Oct 18, 2021 at 2:29
0

Make changes in bellow file config-db.php

nano  /etc/phpmyadmin/config-db.php 

change db server as localhost

$dbserver='localhost';

Its works for me.

0
0

And to save time for anybody who made the same mistake as me - this is the error one gets if one creates a file of credentials on Windows and copies it to Linux. It is easier to create the file in Linux.

Not the answer you're looking for? Browse other questions tagged or ask your own question.