Update record on the same page

0

I have a page PHP that displays the DB information according to a SELECT I made ... now I need that when I click a button I only update 1 table field.

How can I do this update direct, on the same page php , without the need to create another ??

    
asked by anonymous 26.01.2018 / 14:53

2 answers

0

You can use a get variable and use a if($variavel){script...}

ex:

if($_GET['update']){
   $id = $_GET['id'];// lembre-se do escape para sql injection
   $query = 'lógica do update'
}

But the code can get a lot of macros, with several logics in the same file, it might be more interesting to create another one that only updates and then redirects to the listing page.

I think with the concept of SOLID it is easier to understand what each thing really does.

    
26.01.2018 / 14:58
0

I advocate that each process should be done in its proper place, that is, it would make a file for every thing. But by answering your question, making update on a single page is possible, but the request will exist the same way.

Let's imagine the following scenario:

Form File

<form id="frmMeuFormulario" method="post" action="salvar.php">
    <input type="text" name="nome">
    <input type="submit">
</form>

Save action file

<?php
    $nome = $_POST["nome"];
    salvar($nome);
?>

Each file has its own responsibility, this is much better for future maintenance.

But how would this scenario look in a single file? Well, the first time we opened the file, probably the $_POST variable does not exist, so we can use the isset function to check whether or not to execute update :

Single File

<?php
    if (isset($_POST)){
        $nome = $_POST["nome"];
        salvar($nome);
    }
    ?>
    <form id="frmMeuFormulario" method="post">
        <input type="text" name="nome">
        <input type="submit">
    </form>

Notice that in the single file we do not need to have a action , because it will make a POST request in the same file. Also note how harder it was to understand what this file is doing.

    
26.01.2018 / 15:14