What is the best way to pass data between php files

Asked

Viewed 1,659 times

-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 an SQL script and returns an array of data that must be shown, what is the best way to pass this data to the front-end?

php form.:

<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 the $array for the front-end, I already imagined that sessions were not the best choice

  • 2

    In your comments you refute all the answers. This is a sign that your question is not clear. How do these controllers work? When you say "controller," everyone thinks about MVC and the function they have in that pattern. You don’t tell the function of controllers in your application, and why they need to communicate with each other - which is quite unusual in "traditional" controllers, by the way. Also explain about views and how they are loaded.

  • 2

    I can tell you that using sessions for everything you seem to be doing is the worst possible solution.

  • @bfavaretto so I asked that question

  • @bfavaretto rephrased the question I hope it became clearer

  • 4

    I’m reversing your issue because the question has become wider, and invalidated the previous answers.

  • 5

    I have no idea what "pass data between files" is. What kind of data, what kind of files? It would be nice to describe a real scenario. " Passing data between PHP files" is not usually done. What is done is HTML to PHP and vice versa. From PHP to PHP you do include, usually, or save somewhere (and it’s atypical anyway). The question is definitely not clear. I would suggest practical examples, so we have how to help.

  • @Bacco really. I deleted my answer because I may have misinterpreted it. The question is wide.

  • 1

    Another thing. I think that asking for the BEST form becomes a question of opinion many times, because in programming, often, it has several ways of doing. It would be interesting to ask for suggestions like @Bacco said. The best way, who will identify, is you. Because you know the project.

  • 1

    Do you have any code you have made? It may be clearer.

  • @bfavaretto updated the question, I believe my doubt is clearer now

  • Since much of the question is crossed out, it was removing that which you yourself considered important. If you disagree, just undo ;-) Of all sorts, you gain visibility

Show 6 more comments

5 answers

4

The Controller’s function is actually just to 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 you don’t fill the controllers as much.

For example, you can create a Services folder and several subfolders inside.

- Services -- Orders -- Users

I also suggest you take a read on DDD, this can help you have a light:

https://www.devmedia.com.br/domain-driven-design-desenvolva-aplicacoes-com-qualidade/26116

I have something like that, but done in Laravel, but you may have an idea:

inserir a descrição da imagem aqui

Already in this case, you may have a notion of how to organize Services:

inserir a descrição da imagem aqui

Use and abuse the object orientation, gradually you will notice specific benefits and harm, but at first, I believe that these steps can already help.

  • Controllers also serve for database communication, route configuration, error handling and logging, among others

  • 1

    Serve serve, I believe it is not a good practice to centralize everything in it.

  • On the contrary, it decentralizes everything, in several controllers. MVC standard.

  • Sorry, I don’t have enough knowledge to explain my point of view, however, I realize that it is more 'healthy' in terms of maintenance, that controllers do requests/Sponses, as well as specific validation classes (validators) do your part. Repositorios, Services, Presenter, etc.. Each one doing his part, in a way that respects what we learn in SOLID about each one must fulfill a single responsibility.

  • To complement, I realize that the MVC makes the process difficult in very large applications, to the point that it is necessary to think about the DDD, Microservices, etc..

  • Dividing the organization of the project into subfolders of subfolders of subfolders of subfolders is not a solution that I seek, to divide the parts of the project too much leaves it more disorganized in my opinion

  • 3

    Consider that if you have a huge file that does a lot of things and does something wrong in it, instead of just 'breaking' a part of the system, you will break a lot of things. But perfect, it was just a suggestion based on what little I study.

Show 2 more comments

2

Well, from what I understand, you’re using MVC (maybe changing the name of DAO). Following this premise, it is OK to create several controllers in the controllers folder. Actually, this is the idea.

Example of controller and its use:

Controler Client: Methods: Download, Create, Update

Call of methods, URL:

With respect to passing data between controllers, this is actually not common. Normally, the view requests to the Controller, which based on information obtained by models, responses, etc. Sends the information somehow to the View.

Note, are layering

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

The way the controller passes the information to the View depends on it. It can change in every language, platform, framework, etc. I recommend seeing MVC example in your language, in case PHP, correct?

Finally, here are some references. good luck!

https://tableless.com.br/entendendo-o-padrao-mvc-na-pratica/ https://www.devmedia.com.br/introducao-ao-padrao-mvc/29308 What is MVC(Model, View, Controller)?

  • Can you rephrase that answer? I really didn’t understand anything

  • Um, yes, I can, but please tell me which party has the most questions, please. And if possible, see the references at the end of the reply.

  • The way the view and controller pass the data from one to the other is not the case, the pwrgunta is not this, I did not understand the example (list), a look at the issue of the question

  • Look, in fact you don’t have an MVC, for lack of model, but the pattern that established your scripts suggests an MVC. If you prefer, DVC (rsrs). Regarding controller communication with View, I’ll be able to help you better by posting an example of your source. A controller and a view. You can use the Controller as a include for example, and use global variables. Or even, make HTTP requests to the controller for information (More specified)

  • "Regarding controller communication with View", this is not the case I want to know communication from one controller to another controller, pass data from one controller to the other controller, I can’t post code

1


Your architecture is a mess!

Let’s go in parts, before, understanding of HTTP:

  1. the client makes a request
  2. the server receives this request
  3. the server processes this request
  4. ... still processing...
  5. the server responds with data
  6. the client downloads the request
  7. if it is a browser that is receiving HTML, the client renders

So your processing is free. And how do you do the processing? You said you want to "move from one PHP file to another PHP file", which doesn’t exactly make sense... PHP files weren’t meant to talk to each other the way you indicated. It even seems that you wanted a file to be executed, returned to the client and that then made a request right after to rescue the data obtained by the previous script. At least that’s how I understood your line.

Usually what is done is to create a collection of functions in a file more focused on the work of backend and, in the file more frontend, call these functions and display them correctly. To do this, you do not need to separate beautifully across all layers of MVC.

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

  1. to original reply from @Sveen used the principle of separation of interface and bank
  2. to my bitch (which is a variation of the @Sveen response, as I pointed out in the text) only gives an easier maintenance air; I turned a file inclusion usage into a function call

Because the only difference between the two answers was that I used a function, I’m going to focus on the original repsosta, @Sveen’s. The idea here was:

  1. isolate in a component the display of a bank line
  2. in the frontend, first make the database data independent basic statement
  3. then into the core of frontend, obtain the various lines and, for each one, call the line display

Adapting to your case, it could be 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 obtainment. In a way, we separated the "front" and the "back".


About the mess... the use apparent resembles very much something that would be an adaptive page. So, in that case, you wouldn’t need to submit the page for a full reload. An asynchronous reload of the minimally necessary part would be enough. For example, you could separate a <div> for your results and, when you redeem the values, write in this <div> (including discarding the previous values).

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

exemplo de AJAX da wikipedia

To do this, you would need to send the data (the data itself, not the display of it; it is usually transferred in json or xml such data) from a endpoint PHP. On the client side, Javascript would take care of receiving this data, interpreting and then displaying it in the most appropriate way possible.

You will find more about this partial data request by searching about AJAX. By the way, this acronym means (or meant in the origins):

Tosynchronous JavaScript tond XML

In free translation:

Asynchronous Javascript and XML

Here, asynchronous means that the script will call a endpoint on the server and it will respond when possible, having no guarantee of when this occurs. Javascript is the programming language that makes the call and then treats the obtained response. And XML today is understood only as a data transfer, it doesn’t need to be the XML data transfer format.

Another use of AJAX you can see here, in Gitlab:

ajax gitlab

Here, when asking to display a tab, Gitlab starts by doing the asynchronous request, then putting the placeholder of the balls spinning so I think he’s working. When the request is finally completed, a Javascript intercepts the data and tries to display it to me in the best way possible.

  • I expressed myself badly in the question, actually very badly, but I understood what I meant, but I don’t like to use AJAX for everything, I prefer the front to render everything again if necessary, in this case, as I would without AJAX? In this example the user makes a request but without leaving the page and when you have an answer renders on the screen. And if I really want the client to be directed to another page, how to move from that page (controller, for example) to the front?

  • If you go to see, in no time I put some code ajax. The whole code would only address the separation of concerns, without too much concern about trying to fit one model or another. I used the most basic DRY, and I didn’t even try to be that nonrepetitive. For the case you presented, putting more complexity than you need is an anti-standard. You must insert the abstractions as you feel the need, and I did not feel the need according to what was presented.

  • I just put an example, the real system is much more complex. I believe then that I am doing wrong, my codes are divided into an MVC where the view sends a request to the controller, changing page, this is not the most advisable? Instead you should put include arquivo_controller.php instead of passing the data from one page to another? I always thought I should avoid mixing the front with what happens on the back

0

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

Example: question instance, question controller will do all operations relating to questions on 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 like Laravel, there emulate with some methods that HTTP does not support and better organizes requests like PUT for edits, DELETE for removals, GET for searches and POST for insertions.

Use Sessions for login information only!

  • I am seriously abandoning OO in PHP, I know l that MVC is not using it, before trying to answer if it interes enough of the subject. Your answer answers nothing

  • Before you ask a question, remember that no one gets anything by answering your questions. Do you want to abandon OO and use controllers for what? Whether you like it or not, what you’re doing is the MVC model. The MVC model.

  • https://answall.com/questions/104340/php-mixedcodes-orientation- objects-procedural#Answer-104346

  • 1

    MVC can be used without OO. MVC comes before OO.

  • @Guilhermecostamilam. Many Frameworks already bring in their global variable structures, which fluctuates the information between the layers of your application, study the documentation of these frameworks, which will reduce you a lot. But there are many ways to exchange information, whether by converting the data to json structure with json_encore for a javascript variable to handle the display, be you creating a function that already structures html in a variable and you give a include in a page that has an echo for this variable if displayed, since with include variables are still in the pipeline.

-3

Given 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 make 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 if the validation for Success moves the database, either viewing, adding , editing or deleting. Here we 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,
    ],
]);
  • Very abstract question, you can deal with the answer in php with json , angular , see the best tool and knowledge available.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.