How to create a mini database written in php using a text file in json format

Asked

Viewed 1,481 times

4

I was in need of a personal mini database written in PHP to store some internal data of my site, where I would create new properties, change them and delete later if necessary.

In the example below shows how this file would be . txt and how to find/change a specific value (in case you change Mariana’s offline value to online) in JSON.

config.txt

{
   "users": {
      "Mariana": "offline",
      "João": "online"
   }
}

Storage.php:

$method = "[GET ou SET]";
$string = "users/mariana"; // Caminho para a propriedade
$data = file_get_contents("config.txt");

$json = json_decode( $data, true ); // Transforma do JSON em array
$path = explode( "/", $string );
$last = "";

foreach ( $path as $value ) {
    $last = $json[$value]; // Navegar nas propriedades do JSON até a Mariana
}


if ( $method == "SET" ) {
    // Mudar um valor da propriedade
    $last = "online";
    file_put_contents("cofing.txt", $json); // Sava o novo arquvio

    echo "saved";
} else if ( $method == "GET" ) {
    // Somente exibir o valor da propriedade 

    echo $last;
}

I’m not so expert on PHP but if the code was in Javascript it would work, but I prefer PHP to be fast and not conflict when several users try to change some value of config.txt. Could someone help?

  • You’re navigating to the wrong element... You’re only taking the first level of the indices, you need a recursive function to go down one level each time... I’m running out of time to do it now, maybe tomorrow...

  • Aaa truth, I hadn’t realized =Thank you

  • Jeez but after you run the loop, it will no longer save at the end when put in the file

  • Just one question: vc does this pq does not know the existence of sqlite or pq the context you find only allows you to do in/json file?

  • I don’t like the table format of these databases and I think if it was in Json tree format it would be better =)

  • @Iagobruno added the answer.

  • 1

    There are also better alternatives to do this than a .txt. This approach still has simultaneous access problems if several requests run at the same time. Alternatively you can store with Redis, mencached which use a set of key -> value or Mongodb.

  • In addition to the possibility of using Nosql, you can still use the Postgresql JSON type.

Show 3 more comments

3 answers

2

It would be something like this?

Config.json

[  
   {  
      "nome":"Mariana",
      "status":"online"
   },
   {  
      "nome":"Joao",
      "status":"offline"
   },
   {  
      "nome":"Jose",
      "status":"online"
   }
]

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Teste JSON</title>
</head>
<script type="text/javascript">
    function botaoClick(botao){
        document.getElementById('status').value = botao;
        return true;
    }
</script>
<body>
    <form action="storage.php" method="POST">
        Nome: <input type="text" name="nome" />
        <input type="submit" value="online" onclick="return botaoClick(this.value)"/>
        <input type="submit" value="offline" onclick="return botaoClick(this.value)"/>
        <input type="hidden" name="acao" value="SET" />
        <input type="hidden" name="status" id="status" value="" />
    </form>
</body>
</html>

Storage.php

<?php

$metodo = isset($_POST['acao']) ? $_POST['acao'] : "";
$nome = isset($_POST['nome']) ? $_POST['nome'] : "";
$status = isset($_POST['status']) ? $_POST['status'] : "";

$data = file_get_contents("config.json");

$json = json_decode($data);

foreach ($json as $key => $value) {
  if($value->nome == $nome){
    if($metodo == 'SET'){
        $value->status = $status;
        break;
    } else if ($metodo == 'GET') {
        echo $value->status;
        break;
    }
  }
}

$json_enc  = json_encode($json);

file_put_contents('config.json', $json_enc);

echo $json_enc;

1


To work with this type of functionality, a recursive function is the easiest way to do it, for example:

JSON file:

{
   "users": {
      "mariana": "offline",
      "joao": "online"
   }
}

PHP function

function JSONDB($path, $method, $data, &$value = NULL){

   // Separa todas as chaves
   $path = explode('/', $path); 

   // Salva a primeira na variável $key e remove-a da variável $path
   $key = array_shift($path); 

   // Junta todas as chaves em um novo path
   $npath = implode('/', $path);

   // Verifica se é GET e está na última chave
   if ($method == 'GET' && count($path) === 0)
      // Adiciona o valor na variável assinada $value
      $value = $data[$key]; 

   // Verifica se é SET e está na última chave
   else if ($method == 'SET' && count($path) === 0)
      // Seta o valor na chave atual
      $data[$key] = $value; 

   // Verifica se a chave atual não está vazia e é um array
   else if (!empty($data[$key]) && is_array($data[$key]))
      // Desce um nivel no array passando $data[$key] e atualiza o retorno na chave
      $data[$key] = JSONDB($npath, $method, $data[$key], $value); 

   // Nenhuma condição satisfeita, erro (provavelmente caminho errado)
   // Ou dados incorretos
   else 
      // Nada a fazer por aqui
      $value = FALSE; 

   // Retorna os dados para serem salvos
   return $data;
}

Use

// Arquivo com os dados JSON
$file = 'ususarios.json';

// Define método [GET ou SET]
$method = 'SET';

// Caminho para a propriedade
// IMPORTANTE> JSON é Case Sensitive ou seja, diferencia maiúscula de minúscula
// o caminho deve ser escrito da mesma forma como está no arquivo separados por /
$path = 'users/mariana'; 

// Valor a ser alterado caso o método seja GET
// Caso o método seja GET o retorno será colocado nessa variável, 
// então basta definir a variável e passa-la no quarto parâmetro
$val = 'online';

// Pega os dados do json
$data = file_get_contents($file);

// Transforma do JSON em array
$json = json_decode( $data, true ); 

// Executa a função recursiva, todos os dados serão retornado
// caso o método seja GET o valor será colocado na variável do quarto parâmetro
$dados = JSONDB($path, $method, $json, $val);

// Salva caso seja SET
if ($method == 'SET')
   $salva = file_put_contents("cofing.txt", json_encode($dados));

// Imprimindo os dados

echo '<style>pre{display:block; width:80%; margin: 20px auto;padding:10px;background-color:rgba(0,0,0,0.06);border-radius:5px;box-shadow:inset 2px 2px 5px rgba(0,0,0,0.2);}</style>';
echo '<pre>';
if ( $method == 'SET' ) {
    echo $salvo ? 'Arquivo salvo...' : 'Erro ao salvar...';
} else {
    // Somente exibir o valor da propriedade 
    // Obs, a variável $val é o quarto parâmetro passado na função
    // que quando o método for GET, será onde o retorno do GET será armazenado
    var_dump( $val );
}
echo '</pre>';

// Todos os dados
echo '<pre>';
var_dump($dados);
echo '</pre>';

Upshot

Resultado do script

Remarks:

This way of working with data is very primitive, that is, I’m only taking the initial step so that from here you can build your class with methods of data input and output validation, file writing validation and etc.

This type of functionality is very useful for storing settings such as connection to the database and etc. (But of course the file must be protected against external access.

  • Wow, quite complete and different from what I had thought, thank you! I will test later but I think it will work out the way I wanted with some changes =D

  • That’s how Mongodb saves the data?

  • Maybe, but I highly doubt @Wallacemaxters. This form is very simple and like the gmsantos commented in question, here is not implementing competition in the file and in case of many requests at some point will occur a conflict.

-1

I think the ideal, and the safest, would be for you to make a copy of the database file and then make the necessary changes to it. Therefore, I recommend that you use the provided tools themselves to manage the database.

Ex.: If you use the Postgresql as database, you could use the pgAdmin as a management system. In this case, you would have several advantages, such as:

  1. Consistency: When removing/adding/editing information, this information would be updated autmatically in all dependent fields and tables, ensuring that the information is consistent.

  2. Speed: Every database is developed to be very fast, so creating your own query function/language to do this kind of thing would be a waste of time.

  3. Practicality: Using small SQL queries and triggers you could perform a large amount of actions quickly and much more efficiently.

There are several other advantages to using database management systems, these are just a few of them. Therefore, reinforcing what has been said: If you want to manipulate data from a website, use a database management system to do so.

Browser other questions tagged

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