What is the best way to pass data between php files

-3

What is the best way to pass data between back-end and front-end, for example, send a form to the back end, it executes a SQL script and returns an array of data that must be shown, what best way to pass this data to the front end?

form.php:

<form action='./back.php'>
    <input type='text' name='teste'>
    <input type='submit' value='Enviar'>
</form>

back.php:

$con = new mysqli("host", "user", "pass", "db");
$res = $con->query("SELECT * FROM tabela WHERE coluna = '$nome'");
$array = $res->fetch_all();

How to pass $array to the front end, I imagined that sessions were not the best choice

    
asked by anonymous 21.03.2018 / 20:43

5 answers

1

Your architecture is a mess!

Let's start with parts of HTTP:

  • the client makes a request
  • the server receives this request
  • the server processes this request
  • ... still processing ...
  • server responds with data
  • the client downloads the request
  • If it is a browser that is receiving HTML, the client renders
  • Therefore, its processing is free. And how do you do the processing? You said you want to " move from one PHP file to another PHP ", which in essence does not make exactly sense ... PHP files were not meant to talk to each other the way they you indicated. It even seems like you wanted a file to run, go back to the client, and then make a request shortly to retrieve the data obtained by the previous script. At least that's how I understood your speech.

    Normally what you do is create a collection of functions in a file more backend and, in the file facing frontend, call those functions and display them correctly. To do this, you do not need to separate beautifully across all layers of the MVC.

    For example, this separation of data collection from the database and then display was done in that other question :

  • original response from @Sveen used the principle of interface and bank separation
  • my response (which is a variation of the @Sveen response, as I indicated in the text) gives an easier maintenance air; I made a use of including files in function call
  • Since the only difference between the two responses was that I used a function, I'll focus on the original response, @Sveen's. The idea here was:

  • Isolating a line from a bank in a component
  • in frontend , first make the basic statement independent of the database
  • Then, in the middle of frontend , get the various lines and, for each one, call the line display
  • Adapting to your case might look something like this:

    back.php :

    <?php
    function obter_linhas($nome) {
      $con = new mysqli("host", "user", "pass", "db");
      $res = $con->query("SELECT * FROM tabela WHERE coluna = '$nome'");
      return $res->fetch_all();
    }
    ?>
    

    front.php :

    <?php include_onde 'back.php' ?>
    <html>
      <body>
         <h1>Hello, world!</h1>
         <?php
           foreach (obter_linhas($_GET['nome'] as $linha) {
             echo "<li>Olha a primeira posição do array: ".$linha[0]."</li>";
           } 
         ?>
      </body>
    </html>
    

    Ready. We did the visualization of the data independently of the obtaining. In a way, we separate the " front " and the " back ".

    About the mess ... the apparent usage closely resembles something that would be an adaptive page. So, in that case, you would not need to submit the page for a full refill. An asynchronous recharge of the minimally necessary part would be enough. For example, you could separate a <div> for your results and, when you retrieve the values, write that <div> (including discarding the previous values).

    Using this type of thinking, you can have interfaces that display new information without requiring a full page load:

    Forthis,youwouldneedtosendthedata(thedataitself,notthedisplayofthem,usuallyitisusuallytransferredinjsonorxmlthatdata)fromaendpointPHP.Ontheclientside,JavaScriptwouldtakecareofreceivingthisdata,interpretingitandthendisplayingitinthemostappropriatewaypossible.

    YouwillfindmoreaboutthispartialdatarequestbysearchingAJAX.Bytheway,thisacronymmeans(ormeantatthebeginning):

      

    SynchronousJavaScriptandXML

    Freetranslation:

      

    AsynchronousJavaScriptandXML

    Here,asynchronousmeansthatthescriptwillcallanendpointontheserveranditwillrespondwhengiven,havingnoguaranteewhenthisoccurs.JavaScriptistheprogramminglanguagethatmakesthecallandthenhandlestheresponseobtained.AndXMLnowadaysisunderstoodonlyasadatatransfer,itdoesnothavetobethedatatransferXMLformat.

    AnotheruseofAJAXyoucanseehere,inGitLab:

    Here, when prompting to display a tab, GitLab starts by doing the asynchronous request, then placing the placeholder of the balls spinning so I think it's working. When the request is finally terminated, JavaScript intercepts the data and tries to display it to me in the best possible way.

        
    28.04.2018 / 09:03
    4

    The function of the Controller actually is to only handle HTTP calls to the application. An alternative for you would be to pass the business rules to a layer (directory) called Services. So you centralize these logics as services, and do not stuff the controllers as much.

    You can, for example, create a Services folder and several sub-folders within.

    - Services -- Orders -- Users

    I also suggest you give a read about DDD, this can help you have a light:

    link

    I have something like this, but done in Laravel, but you can get an idea:

    Inthiscase,youcangetasenseofhowtoorganizeServices:

    Use and abuse object orientation, you will gradually realize specific benefits and harms, but at the outset, I believe these steps can already help.

        
    21.03.2018 / 21:30
    2

    Well, from what I understand, you're using MVC (maybe changing the name of DAO). Following this premise, you have no problem creating multiple controllers in the controllers folder. In fact, this is the idea.

    Controller example and its use:

    Customer Controller: Methods: Get, Create, Update

    Call methods, URL:

    • link - GET, where 5 is a client id, for example
    • link - POST (JSON for example)
    • link - POST (JSON for example)

    In relation to passing data between controllers, this is not really common. Normally, the view makes requests to the Controller, which based on the information obtained by models, respositories, etc. Send the information in some way to the View.

      

    Note, they are layers

    The way the view passes information to the controller can be GET, POST, PUT, etc.

    As the controller passes the information to the View, it depends. Can change in each language, platform, framework, etc. I recommend seeing an example in MVC in your language, in this case PHP, correct?

    Finally, there are some references. good luck!

    link link What is MVC (Model, View, Controller)?

        
    21.03.2018 / 21:39
    0

    You must separate into multiple controllers (remember that it is object-oriented, unstructured). You define instances and they will have 1 controller, each.

    Example: Question Instance, Question Controller will do all the operations pertaining to the questions in your system.

    What you are looking for is called MVC (Model (your DAO), Vision, Controller). Use POST for insert and GET requests for read operations.

    If you prefer to use a framework such as Laravel, it emulates with some methods that HTTP does not support and better organize requests such as PUT for edits, DELETE for removals, GET for searches and POST for inserts.

    Use Sessions only for login information!

        
    21.03.2018 / 21:32
    -3

    In front of what I see in the question, is a form for a MySQL, you can use GET to list there you will have your data passed by URL where you should leave them friendly, you can use POST to add, PUT to edit and DELETE to delete, this FORM is very generic but I advise using an MVC to handle between your Front-End and Back-End, but if it is only for these pages, you will need to have the form sending the data to a page that will validate this data, include the database connection on this page and whether the validation is Success will tinker in the database, either by viewing, adding, editing or deleting. Here I use PHP and Angular as an example:

    // Incluindo biblioteca e configuração do banco de dados
    require 'vendor/autoload.php';
    require 'config/database.php';
    
    // Retornando os dados no formato JSON
    echo json_encode([
        'registros' => $registros,
        'paginacao' => [
            'registros_por_pagina' => $registrosPorPagina,
            'pagina_atual'         => $paginaAtual,
            'total_registros'      => $totalRegistros,
        ],
    ]);
    
        
    28.04.2018 / 10:19