How to create an installer for tables and connection to the bank?

0

I would like to thank you in advance for your cooperation. I know it's possible, but I still have no idea how to do it. I have a script but it will be used for sale, but I would like the script in the middle to have a way to ask the client what the connection data is like (localhoat, root, pass, BD) and after the connection is successfully inserted tables in the database.

Similar to the beginning of WordPress.

    
asked by anonymous 21.02.2016 / 15:05

1 answer

2

Modifications within the main system

In your script (the system that will be sold), it should check the config.inc.php file, which in our case will (or should be) in the system folder.

if (!file_exists('system/config.inc.php')) {
    echo "Clique <a href='./install/' title='Iniciar instalacao'>aqui</a> para iniciar a instalacao do sistema.";
    exit;
}

Explaining the code above: it will check if the config.inc.php file exists inside the system folder. Notice that we put a negation operator ! before the function, that is, if it does not exist it returns true and executes the code inside the condition, which only displays a message and a link to the install/ folder (which will contain the installation system) and stops executing the script using exit.

If the config.inc.php file already exists, it is also interesting to place a new condition (below the previous one) to check the install folder exists, if so, we will force the user to delete it in order to use the system , since keeping this folder would be a security risk.

if (file_exists('install/')) {
    echo "Por favor, delete a pasta install.";
    exit;
}

That's right, it's just the changes within the system that you're going to sell. Now we will have to create a new system to do the installation.

It is interesting that it does not depend on any files on the main system, that is, all css files, images, connection files with bank, functions, anyway ... everything must exist inside the install folder to be used only by the installer.

Creating the installer

Create a index.php file inside the install folder. This file will be responsible for calling the pages according to the step that will be passed via $_GET . See the template below and modify as needed.

<?php

    $step = (isset($_GET['step'])) ? (int) $_GET['step'] : null;

    //Quantidade de etapas que seu instalador irá ter.
    $qntEtapas = 3;

    if (empty($step) || $step > $qntEtapas) {
        header('Location: ./?step=1');
    }

    //Crie uma pasta chamada step e dentro dela, coloque as páginas seguindo o modelo: pagina-1.php pagina-2.php pagina-3.php, conforme a quantidade de etapas.
    require_once 'step/pagina-' . $step . '.php';

Now you have to build the layout of the pages of each step, which is a bit off topic, so I will not tell you how. But, I'll give you a hint: the pages of each step will usually only have the form different, so it would be interesting if you create 2 .php files called header.php and footer.php , and include them, leaving the pages of the cleanest steps and making maintenance easier.

Below is an example of a step page (with the same fields as the image you posted to WordPress).

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $database = (isset($_POST['database'])) ? trim($_POST['database']) : null;
    $username = (isset($_POST['username'])) ? trim($_POST['username']) : null;
    $password = (isset($_POST['password'])) ? trim($_POST['password']) : null;
    $hostname = (isset($_POST['hostname'])) ? trim($_POST['hostname']) : null;
    $dbprefix = (isset($_POST['dbprefix'])) ? trim($_POST['dbprefix']) : null;

    if (!empty($database) || !empty($username) || !empty($hostname)) {

        //Nesse caso em especifico, precisamos fazer uma conexão com o banco
        //usando os dados informados pelo usuário, para ter certeza de que estão
        //corretos.

        function dbTest($host, $user, $pass, $db) {
            try {
                $pdo = new PDO("mysql:host={$host};dbname={$db};charset=utf8", $user, $pass);
                return $pdo;
            } catch (PDOException $e) {
                return false;
            }
        }

        if (dbTest($hostname, $username, $password, $database)) {

            //Se a conexão der certo, cria (caso não exista) o arquivo config.inc.php
            //dentro da pasta system e escreve os dados nele.
            file_put_contents('../system/config.inc.php',
                '<?php'
              . '    $hostname = ' . "'{$hostname}'; \n"
              . '    $username = ' . "'{$username}'; \n"
              . '    $password = ' . "'{$password}'; \n"
              . '    $database = ' . "'{$database}'; \n"
              . '    $dbprefix = ' . "'{$dbprefix}'; \n"
            );

            //Redireciona para próxima etapa, se for o caso.
            header('Location: ./?step=2');
        } else {
            echo 'Desculpe, mas não foi possível conectar-se ao banco de dados informado.';
        }
    } else {
        echo 'Por favor, preencha os campos corretamente...';
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
        <title>Instalando sistema | Etapa 1 de 1</title>
    </head>
    <body>
        <form action="" method="post">
            <label for="database">Nome do banco</label>
            <input type="text" id="database" name="database"><br>
            <label for="username">Usuário</label>
            <input type="text" id="username" name="username"><br>
            <label for="password">Senha</label>
            <input type="password" id="password" name="password"><br>
            <label for="hostname">Servidor MySQL</label>
            <input type="text" id="hostname" name="hostname" value="localhost"><br>
            <label for="dbprefix">Prefixo da tabela</label>
            <input type="text" id="dbprefix" name="dbprefix">
            <hr>
            <button type="submit">Ir para próxima etapa</button>
        </form>
    </body>
</html>

Note that the big X of the question is the file_put_contents function, it is the one that will write the data passed in the specified file.

To insert tables in the database informed by the user, you just have to execute a query normally, only putting the SQL code to create it.

The SQL code you should do manually, or create the tables via phpMyAdmin, MySQL Workbench or any other program that helps you with this, then copy the generated SQL and put in your script to run as a normal query. >

It is the same thing as giving a SELECT * FROM usuarios WHERE id = 1; only changes the SQL command.

That's basically it. Now it is to take a look at what was said here, and improve the code to suit your needs.

Recommended Readings

function file_exists
Ternary operator in PHP
function file_put_contents

    
22.02.2016 / 21:22