Link my site on netlify with a database on another host

Hello, I want to link a site on the netlify host to a database linked directly to a form on my site. This database is on the host Alwaysdata.

  <?php
// Connect to the database
$servername = "phpmyadmin.alwaysdata.com";
$username = "root";
$password = "Azerty";
$dbname = "test_reservation";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
     die("Database connection error: " . $conn->connect_error);
}

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
     // Retrieve the data sent by the form
     $name = $_POST["name"];
     $email = $_POST["email"];
     $phone = $_POST["phone"];
     $destination = $_POST["destination"];
     $category = $_POST["category"];
     $date_depart = $_POST["date_depart"];
     $date_return = $_POST["date_return"];
     $nb_people = $_POST["nb_people"];
     $comments = $_POST["comments"];

     // Prepare the SQL insertion query
     $sql = "INSERT INTO reservation (name, email, telephone, destination, category, date_departure, date_return, nb_people, comments)
             VALUES ('$name', '$email', '$telephone', '$destination', '$category', '$date_departure', '$date_return', '$nb_persons', '$comments')";

     // Execution of the SQL query
     if ($conn->query($sql) === TRUE) {
         echo "Reservation saved successfully.";
     } else {
         echo "Error saving reservation: " . $conn->error;
     }
}

// Close the connection to the database
$conn->close();
?>

And the following API.php page:

<?php
header('Content-Type: application/json');

// Step 2: Include the connection file
require_once 'login.php';

// Step 3: Retrieve all reservations
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
     $query = $con->query("SELECT * FROM reservation");

     if ($query) {
         $reservations = [];
         while ($row = $query->fetch_assoc()) {
             $reservations[] = $row;
         }

         $response['error'] = false;
         $response['reservations'] = $reservations;
         $response['message'] = 'Retrieval of reservations was successful.';
     } else {
         $response['error'] = true;
         $response['message'] = 'Failed to retrieve reservations.';
     }

     echo json_encode($response);
}

// Retrieve a reservation by name
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'])) {
     $name = $_POST['name'];
     $query = $con->prepare("SELECT * FROM reservation WHERE name =?");
     $query->bind_param("s", $name);

     if ($query->execute()) {
         $result = $query->get_result();

         if ($result->num_rows > 0) {
             $reservation = $result->fetch_assoc();
             $response['error'] = false;
             $response['reservation'] = $reservation;
             $response['message'] = 'Retrieval of reservation by name was successful.';
         } else {
             $response['error'] = true;
             $response['message'] = 'No reservation found with this name.';
         }
     } else {
         $response['error'] = true;
         $response['message'] = 'Failed to retrieve reservation by name.';
     }

     echo json_encode($response);
}

$con->close();

// Example of sending a POST request to api.php from JavaScript to retrieve a reservation by name
const reservationName = 'John Doe'; // Replace 'John Doe' with the desired name

fetch('api.php', {
   method: 'POST',
   headers: {
     'Content-Type': 'application/json'
   },
   body: JSON.stringify({
     name: reservationName
   })
})
   .then(response => response.json())
   .then(data => {
     // Process response data
     console.log(data);
   })
   .catch(error => {
     // Error management
     console.error('An error has occurred:', error);
   });

?>

I have the following error:

This page of [
].netlify.app cannot be found
No web page found at: https[
]/processing.php

HTTP ERROR 404

Yet the page is located in the same directory as the other files in my github repository.

And the netlify deploy log tells me everything is “complete” (initialization, building, deployment, cleanup and post-processing)

Can you clarify the error for me please? Thank you, I wish you a good day.

@LD77 You won’t be able to use the scripts that you’ve got as there is no runtime PHP with Netlify.

You can only use PHP at build time, for example with PHP based static site generators.

You could connect to the database and do what you’re trying to do, but you would need to either host the PHP API elsewhere and proxy to it with Netlify redirects, or recreate it with Serverless Functions.

Alright, thanks for your response. I focused on the API:

connection.php contains the following code:

<?php //modify $dbname = "[B]user[/B]_reservation"; $host = "mysql-[B]user[/B].alwaysdata.net"; $username = "ttt"; $password = "ttt"; $con = mysqli_connect($host, $username, $password, $dbname); // Verification if (!$con) { echo "Message: Unable to connect to DB"; die(); } else { echo "Connection successful!"; } ?>[/CODE]

api.php contains the following code: [CODE]<?php
header(‘Content-Type: application/json’);

// Allow access from a specific domain
header(‘Access-Control-Allow-Origin: https://melun-voyage.netlify.app’);
// Allow GET and POST methods
header(‘Access-Control-Allow-Methods: GET, POST’);
// Allow content with specified Content-Type headers
header(‘Access-Control-Allow-Headers: Content-Type’);

// Step 2: Include the connection file
require_once DIR . ‘/login.php’;

// Connect to the database
$dbname = “user_reservation”;
$host = “mysql-user.alwaysdata.net”;
$username = “ttt”;
$password = “ttt”;

$con = new mysqli($servername, $username, $password, $dbname);

if ($con->connect_error) {
die("Database connection error: " . $con->connect_error);
}

// Retrieve all reservations
if ($_SERVER[‘REQUEST_METHOD’] === ‘GET’) {
$query = $con->query(“SELECT * FROM reservation”);

 if ($query) {
     $reservations = [];
     while ($row = $query->fetch_assoc()) {
         $reservations[] = $row;
     }

     $response['error'] = false;
     $response['reservations'] = $reservations;
     $response['message'] = 'Retrieval of reservations was successful.';
 } else {
     $response['error'] = true;
     $response['message'] = 'Failed to retrieve reservations.';
 }

 echo json_encode($response);

}

// Retrieve a reservation by name
if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’ && isset($_POST[‘name’])) {
$name = $_POST[‘name’];
$query = $con->prepare(“SELECT * FROM reservation WHERE name =?”);
$query->bind_param(“s”, $name);

 if ($query->execute()) {
     $result = $query->get_result();

     if ($result->num_rows > 0) {
         $reservation = $result->fetch_assoc();
         $response['error'] = false;
         $response['reservation'] = $reservation;
         $response['message'] = 'Retrieval of reservation by name was successful.';
     } else {
         $response['error'] = true;
         $response['message'] = 'No reservation found with this name.';
     }
 } else {
     $response['error'] = true;
     $response['message'] = 'Failed to retrieve reservation by name.';
 }

 echo json_encode($response);

}

$con->close();
?>

                                                                                   [/CODED]

the proctfile contains the following code: web:sh run.sh .

composer.json contains the following:
{}

run.sh the following code: #!/bin/bash
php api.php

This therefore means*:

that the error message “No web processes running” indicates that there are no web processes running for your application. This may be due to a problem with your Procfile or an incorrect configuration.
when the web process is started with the command sh run.sh ., there is an error in the api.php file on line 12. The error indicates that it was not possible to open the connection file .php. Make sure that the connection.php file is present in the same directory as api.php on Heroku.

However, the connection.php file and api.php are located in the same folder.

Thank you in advance for your help.

However I have the following errors: C:\laragon\www\littleAPI>heroku logs --tail --app api-avion
2023-07-02T12:18:27.200704+00:00 heroku[router]: at=errorcode=H14 desc=“No web process running” method=GET path=“/” host=api- airplane-7c409a1420d5.herokuapp. com request_id=5e3a22e5-8bf8-4502-9341-5838f38c76f0 fwd=“162.255.45.108” dyno=connect=service=status=503 bytes=protocol=https
2023-07-02T12:18:28.118456+00:00 heroku[router]: at=errorcode=H14 desc=“No web process running” method=GET path=“/favicon.ico” host =api-avion-7c409a1420d5 .herokuapp.com request_id=d85101ea-7da7-4252-863b-71082af1e3cc fwd=“162.255.45.108” dyno= connect= service= status=503 bytes= protocol=https
2023-07-02T12:30:23.069830+00:00 app[api]: Scaling web@1:Basic by user
2023-07-02T12:30:24.163774+00:00 heroku[web.1]: Starting process with command sh run.sh .
2023-07-02T12:30:24.987531+00:00 app[web.1]: PHP Warning: require_once(connection.php): Failed to open stream: No such file or directory in /app/api .php at line 12
2023-07-02T12:30:24.987558+00:00 app[web.1]: PHP Fatal Error: Undetected error: Failed to open required ‘connection.php’ (include_path=‘.:’) in /app /api.php:12
2023-07-02T12:30:24.987559+00:00 app[web.1]: Stack trace:
2023-07-02T12:30:24.987559+00:00 app[web.1]:#0 {main}
2023-07-02T12:30:24.987560+00:00 app[web.1]: thrown in /app/api.php on line 12
2023-07-02T12:30:25.117184+00:00 heroku[web.1]: Process terminated with status 255
2023-07-02T12:30:25.147767+00:00 heroku[web.1]: Status changed from booting to crashing
2023-07-02T12:30:25.153305+00:00 heroku[web.1]: Status changed from crashed to starting
2023-07-02T12:30:26.045555+00:00 heroku[web.1]: Starting process with command sh run.sh .
2023-07-02T12:30:26.949203+00:00 app[web.1]: PHP Warning: require_once(connection.php): Failed to open stream: No such file or directory in /app/api .php at line 12
2023-07-02T12:30:26.949222+00:00 app[web.1]: PHP Fatal Error: Uncaught Error: Failed to open required ‘connection.php’ (include_path=‘.:’) in /app /api.php:12
2023-07-02T12:30:26.949223+00:00 app[web.1]: Stack trace:
2023-07-02T12:30:26.949223+00:00 app[web.1]:#0 {main}
2023-07-02T12:30:26.949225+00:00 app[web.1]: thrown in /app/api.php on line 12
2023-07-02T12:30:27.078753+00:00 heroku[web.1]: Process terminated with status 255
2023-07-02T12:30:27.112988+00:00 heroku[web.1]: Status changed from booting to crashing
2023-07-02T12:30:52.728877+00:00 app[api]: scaled to web@0:Basic by user
2023-07-02T12:30:53.238898+00:00 heroku[web.1]: Status changed from crashed to stopped
2023-07-03T08:26:42.000000+00:00 app[api]: Build started by user
2023-07-03T08:26:53.000000+00:00 app[api]: Build successful
2023-07-03T08:26:53.506901+00:00 app[api]: Deploy b4e882b5 by user
2023-07-03T08:26:53.506901+00:00 app[api]: v4 version created by user *
2023-07-03T08:35:50.000000+00:00 app[api]: Build started by user
2023-07-03T08:36:00.909707+00:00 app[api]: Deploy a6c7396c by user
2023-07-03T08:36:00.909707+00:00 app[api]: v5 version created by user
2023-07-03T08:36:01.000000+00:00 app[api]: Build successful
2023-07-03T10:49:02.524097+00:00 app[api]: Starting process with ls command by user
2023-07-03T10:49:03.767188+00:00 heroku[run.6796]: Waiting customer
2023-07-03T10:49:03.907833+00:00 heroku[run.6796]: Status changed from boot to top
2023-07-03T10:49:06.090223+00:00 heroku[run.6796]: Starting process with ls command
2023-07-03T10:49:09.640211+00:00 heroku[run.6796]: Process terminated with status 0
2023-07-03T10:49:09.670128+00:00 heroku[run.6796]: Status changed from until completed
2023-07-03T11:04:20.000000+00:00 app[api]: Build started by user
2023-07-03T11:04:31.950591+00:00 app[api]: Deploy d4eab293 by user
2023-07-03T11:04:31.950591+00:00 app[api]: v6 version created by user
2023-07-03T11:04:32.000000+00:00 app[api]: Build successful
2023-07-03T11:07:38.060136+00:00 heroku[router]: at=errorcode=H14 desc=“No web process running” method=GET path=“/” host=api- airplane-7c409a1420d5.herokuapp. com request_id=8bc9ccbb-0231-475f-b40c-894e05e8d102 fwd=“90.25.216.195” dyno= connect= service= status=503 bytes= protocol=h

@LD77 As you’re trying to host runtime PHP with Heroku, your best bet would be seeking assistance for it from Heroku directly, or a community that’s more familiar with PHP & Heroku.

Hi, @LD77. This support guide is the usual starting place for this type of question:

If there are other questions after reading that, please let us know.

Sorry for not having translated into English

voici le code de api.php :<?php
header(‘Content-Type: application/json’);

// Autoriser l’accĂšs depuis un domaine spĂ©cifique
header(‘Access-Control-Allow-Origin: https://melun-voyage.netlify.app’);
// Autoriser les méthodes GET et POST
header(‘Access-Control-Allow-Methods: GET, POST’);
// Autoriser le contenu avec les en-tĂȘtes Content-Type spĂ©cifiĂ©s
header(‘Access-Control-Allow-Headers: Content-Type’);

// Étape 2 : Inclure le fichier de connexion
require_once DIR . ‘/connexion.php’;

// Connexion à la base de données
$dbname = “user_reservation”;
$servername = “mysql-user.alwaysdata.net”;
$port = “3306”;
$username = “user”;
$password = “”;

$con = new mysqli($servername, $username, $password, $dbname, $port);

// Vérifier les erreurs de connexion
if ($con->connect_error) {
$response[‘error’] = true;
$response[‘message’] = "Erreur de connexion Ă  la base de donnĂ©es : " . $con->connect_error;
echo json_encode($response);
exit;
}

// Récupérer toutes les réservations
if ($_SERVER[‘REQUEST_METHOD’] === ‘GET’) {
$query = $con->query(“SELECT * FROM reservation”);

if ($query) {
    $reservations = [];
    while ($row = $query->fetch_assoc()) {
        $reservations[] = $row;
    }

    $response['error'] = false;
    $response['reservations'] = $reservations;
    $response['message'] = 'La récupération des réservations a réussi.';
} else {
    $response['error'] = true;
    $response['message'] = 'Échec de la rĂ©cupĂ©ration des rĂ©servations : ' . $con->error;
}

echo json_encode($response);

}

// Récupérer une réservation par nom
if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’ && isset($_POST[‘nom’])) {
$nom = $_POST[‘nom’];
$query = $con->prepare(“SELECT * FROM reservation WHERE nom = ?”);
$query->bind_param(“s”, $nom);

if ($query->execute()) {
    $result = $query->get_result();

    if ($result->num_rows > 0) {
        $reservation = $result->fetch_assoc();
        $response['error'] = false;
        $response['reservation'] = $reservation;
        $response['message'] = 'La récupération de la réservation par nom a réussi.';
    } else {
        $response['error'] = true;
        $response['message'] = 'Aucune réservation trouvée avec ce nom.';
    }
} else {
    $response['error'] = true;
    $response['message'] = 'Échec de la rĂ©cupĂ©ration de la rĂ©servation par nom : ' . $con->error;
}

echo json_encode($response);

}

$con->close();
?>

Blockquote

Preformatted text

`

Voici le code de connexion.php : <?php
// Connexion à la base de données
$dbname = “user_reservation”;
$servername = “mysql-user.alwaysdata.net”;
$port = “3306”;
$username = “user”;
$password = “”;

try {
$con = new mysqli($servername, $username, $password, $dbname, $port);
if ($con->connect_error) {
throw new Exception("Impossible de se connecter à la base de données : " . $con->connect_error);
}
echo “Connexion effectuĂ©e avec succĂšs!”;
} catch (Exception $e) {
echo "Erreur de connexion à la base de données : " . $e->getMessage();
die();
}
?>

Les codes ci-dessus concernent uniquement l’API.

Le code ci-dessous concerne la page traitement.php de mon site netlify : <?php
// Connexion à la base de données
$dbname = “user_reservation”;
$servername = “mysql-user.alwaysdata.net”;
$port = “3306”;
$username = “user”;
$password = “”;

// Étape 2 : Inclure le fichier de connexion
require_once DIR . ‘/connexion.php’;

$conn = new mysqli($servername, $username, $password, $dbname, $port);

if ($conn->connect_error) {
die("Erreur de connexion à la base de données : " . $conn->connect_error);
}
// Vérification si le formulaire est soumis
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
// Récupération des données envoyées par le formulaire
$nom = $_POST[“nom”];
$email = $_POST[“email”];
$telephone = $_POST[“telephone”];
$destination = $_POST[“destination”];
$categorie = $_POST[“categorie”];
$date_depart = $_POST[“date_depart”];
$date_retour = $_POST[“date_retour”];
$nb_personnes = $_POST[“nb_personnes”];
$commentaires = $_POST[“commentaires”];

// PrĂ©paration de la requĂȘte SQL d'insertion
$sql = "INSERT INTO reservation (nom, email, telephone, destination, categorie, date_depart, date_retour, nb_personnes, commentaires)
        VALUES ('$nom', '$email', '$telephone', '$destination', '$categorie', '$date_depart', '$date_retour', '$nb_personnes', '$commentaires')";

// ExĂ©cution de la requĂȘte SQL
if ($conn->query($sql) === TRUE) {
    echo "Réservation enregistrée avec succÚs.";
} else {
    echo "Erreur lors de l'enregistrement de la réservation : " . $conn->error;
}

}

// Fermeture de la connexion à la base de données
$conn->close();
?>

Blockquote

Pourquoi, ayant dĂ©clarĂ© $servername, dont je pense de la meilleure des maniĂšres, j’ai toujours cette erreur ?

Merci d’avance pour votre rĂ©ponse, j’essaierai entre-temps de piocher d’autres informations sur internet et sur divers forums.

@LD77 As per my original response and the support guide linked to by @luke, Netlify doesn’t provide runtime PHP hosting, so you won’t be able to get assistance with this here.

1 Like