How to crud with php using JSON?

Asked

Viewed 342 times

-1

I am doing a project where I will need to do a CRUD using JSON as data storage. I’m already able to visualize the data and enter it. How can I do Edit and delete? I have no idea. I’m new and I don’t know how to do it. I’ll leave an example of how my Json for you to see what could be done.

JSON:

[{"codigo":"4336","nome":"teste1","email":"[email protected]","telefone":"32132132"},{"codigo":"4248","nome":"teste2","email":"[email protected]","telefone":"321321231"}]

I already have the listing of the data and I already have the edit page Done, in it will have the form fields already filled with the information of the xml data. I’m passing the code (which is unique), via get, so try to get the data, so the url is like this:

http://localhost/Meuprojeto/Edit.php? id=4336

But I do not know how to bring the data to the fields and do Edit, nor do I know how to delete them too, if the user wishes.

screen print: inserir a descrição da imagem aqui

EDIT 1: I’ve managed to make the value appear in the fields, but I still don’t know how to do Edit and delete. Please help me.

EDIT 2: My code from the archive:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Editar Colaborador - TEKNISA</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="estilo.css" rel="stylesheet">
  </head>

  <body>

    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container">
        <a href="index.html" class="navbar-brand"><img src="imagens/logo.png" width="230"></a>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse d-flex justify-content-end" style="flex-grow: 0" id="navbarText">
          <span class="navbar-text">
            Editar colaboradores
          </span>
        </div>
      </div>
    </nav>

    <div class="container">
      <div class="card text-center mt-5">
        <div class="card-header">
          Editar
        </div>
        <div class="card-body">

        <form action="editar_colaborador.php" method="post">
            <div class="row">
              <?php 
                if(file_exists("bd/colaboradores.json")){
                  $arquivo = file_get_contents('bd/colaboradores.json');
                  $json = json_decode($arquivo);

                  foreach($json as $registro):
                    if($registro->codigo == $_GET['id']){
                      echo "<div class='col'>";
                      echo "<input type='text' name='nome' id='nome' class='form-control' required placeholder='Nome' value='" . $registro->nome . "' >";
                      echo "</div>";

                      echo "<div class='col'>";
                      echo "<input type='text' name='email' id='email' class='form-control' required placeholder='E-mail' value='" . $registro->email . "' >";
                      echo "</div>";

                      echo "<div class='col'>";
                      echo "<input type='text' name='telefone' id='telefone' class='form-control' required placeholder='Telefone' value='" . $registro->telefone . "' >";
                      echo "</div>";
                    }
                  endforeach;
                }
              ?>
            </div>

            <br>
            <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
            <a href="index.php" class="btn btn-danger">CANCELAR</a>
            <button type="submit" name="editar" class="btn btn-success">CONFIRMAR</button>
        </form>

        </div>
      </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>

EDIT 3:

I was with this line of reasoning(it’s wrong, it’s only for you to complete, in case I’m on the right track):

<?php 
  if(file_exists("bd/colaboradores.json")){

    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $telefone = $_POST['telefone'];

    $arquivo = file_get_contents('bd/colaboradores.json');
    $json = json_decode($arquivo);

    foreach($json as $registro):
        if($registro->codigo == $_GET['id']){

          $novos_dados = array($registro->nome = $nome,
            $registro->email = $email,
            $registro->telefone = $telefone
          );

        }
    endforeach;
  }else{
    header('Location: index.php');
  }
?> 
  • json Decode and do a foreach and pass the update

1 answer

0

Answers on the question with json

public function update(Request $request){

       $dados = Model::find($request->get('id'));

       foreach(json_decode($request->json) as $dado){
          $dados->nome -> $dado['nome']; // assim continua faz o teste e me retorna
       }

       $dados->save();
}
  • look, I’m a beginner and I don’t really know how to use it, but when I put this function gave an error in "public". Look: Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting end of file. I’ll leave my html there in the question, to better understand how you are.

  • @Samuk put in question the dd($request->all());

  • I’m sorry, I don’t understand Lucas. What should I pass as a parameter? And what is this Model? I tried to pass the Json directly, instead of using the request and having to use ma Function, but I didn’t understand it well.

  • I’ll leave it as I was asking the question... (you’re wrong... it doesn’t work, but it’s just for you to understand how was my line of reasoning)

  • @Samuk why do you store friend files? I’m sorry I can’t help you ta very confused your doubt and your code.

Browser other questions tagged

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