Send Array to BD

Asked

Viewed 333 times

0

Good afternoon, you guys. I’m trying to pass an array that retrieves a JSON to the BD, but I’m not able to identify the objects of the Array, I think I’m doing something wrong, I did some tests with foreach but I was not successful, follow the Cod’s.

HTML

<?php include('header.php'); ?>
<script type="text/javascript" src="script/script.js"></script>

<title>DataTable</title>

<style>
tfoot input {
width: 100%;
padding: 0;
box-sizing: border-box;
color: #FFFFFF;
}
tfoot {
display: table-footer-group;
}
</style>

<?php include('container.php'); ?>
<div class="container">
<h2>DataTable</h2>
<div class="row">
<table id="example" class="display" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>ID</th>
      <th>Data</th>
      <th>Horário</th>
      <th>Nº Telefone</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th></th>
      <th class="selectedDate" id="1">Data</th>
      <th></th>
      <th></th>
    </tr>
  </tfoot>
  </table>
  </div>
  </div>
  <?php include('footer.php'); ?>

script js.

// _START_ DataTable
var table = $('#example').DataTable({
"bProcessing": true,
"sAjaxSource": "data.php",
"bPaginate": true,
"sPaginationType": "full_numbers",
"iDisplayLength": 5,
"autoWidth": true,
"aoColumns": [
  {mData: [0]},
  {type: 'date-br',
  targets: 1},
  { "orderable": false, "targets": 2 }, // remove a ordenação
  { "orderable": false, "targets": 3 },
  ]
  });

// função para retornar o dados da tela em json
setInterval(function () {
var table3 = $('#example').tableToJSON();
var request =  $.ajax({
  method: "POST",
  url: "teste.php",
  data: { array: table3},
  dataType: "html"
})    
request.done(function(resposta) {
  //resposta servidor
  console.log(resposta)
});
}, 6000); // está em segundos

php test.

<?php
$array = ($_POST['array']);
print_r($array);

Array

Array
(
[0] => Array
    (
        [ID] => 
        [Data] => 
        [Horário] => 
        [Nº Telefone] => 
    )
[1] => Array
    (
        [ID] => 8010
        [Data] => 27/12/2017
        [Horário] => 14:58:27
        [Nº Telefone] => 1231530337
    )
[2] => Array
    (
        [ID] => 8010
        [Data] => 27/12/2017
        [Horário] => 14:56:52
        [Nº Telefone] => 1231530337
    )
)
  • Need to do a foreach on $array then access the keys you want.

  • I had done it before but I ended up passing wrong value and I thought it was not going right, I reviewed the structure again and it worked .-. foreach($array as $key => $value)&#xA;{&#xA; var_dump($key." - ".$value["ID"]);&#xA; var_dump($key." - ".$value["Data"]);&#xA; var_dump($key." - ".$value["Horário"]);&#xA; var_dump($key." - ".$value["Nº Telefone"]);&#xA;}

  • RESULT string(4) "0 - "&#xA;string(4) "0 - "&#xA;string(4) "0 - "&#xA;string(4) "0 - "&#xA;string(8) "1 - 8010"&#xA;string(14) "1 - 27/12/2017"&#xA;string(12) "1 - 14:58:27"&#xA;string(14) "1 - 1231530337"&#xA;string(8) "2 - 8010"&#xA;string(14) "2 - 27/12/2017"&#xA;string(12) "2 - 14:56:52"&#xA;string(14) "2 - 1231530337"&#xA;string(8) "3 - 8010"&#xA;string(14) "3 - 27/12/2017"&#xA;string(12) "3 - 10:53:14"&#xA;string(15) "3 - 11993229733" in this case I can already do the data Insert in the database ? Thank you

  • @Diogomoura Da to see nothing here in the comments, better edit your question.

  • @Diogomoura, I studied this Postgresql, I created a database with a table links but it was missing to create the table callcent_queuecalls so I can test. If you can provide sql to create this table and a ìnsert with the data, would save me time because I will have to study the types of data to stay in line. However, I edited my reply by publishing the test.php page that is working round.

  • I just updated GIT with the Insert, you can send me the SQL of the table you created please, I tried to insert here with this code that you updated in my test database and it didn’t work, it may be that my test comic is wrong, thanks.

  • As I don’t know the Postgresql data types yet, I created 4 fields, Cod, date, time and phone all type character(15). I changed the array in the answer and I believe it stayed as you put in your question.

  • Create a test table with 4 fields cod, data, hora e telefone and run my answer code to see if you enter.

  • @Leocaracciolo I had done the tests before with the manual array and they insert normally, I again with your Cód and ta OK sent to the database, but then when I pull the data from my table as array it n sends to the database and the array is equal to your Cod gave a print_r and the structure is the same as what is in my question, I put to take the data for a certain time in the script, is it not activating my test.php page that does the sending of data to the BD ? at least the print_r php page is returning in the console.

  • @Leocaracciolo CONSEGUI!! I did the following:, $array = ($_POST['array']);&#xA; $json_e = json_encode($array, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);&#xA; $json_d = json_decode($json_e, true);&#xA; print_r ($json_d); //teste

  • Beauty, success there for you!!!

  • @Leocaracciolo thanks a lot for the help, success for you too.

Show 7 more comments

1 answer

0


PHP php test.

I did a test with the array as shown in the code below, and it is working round

$db = pg_connect("host=localhost port=5432 dbname=call_lost user=diogom password=morfeu00");

    $array = (

    Array
    (
    "0" => Array
        (
            "ID" => "",
            "Data" => "",
            "Horário" => "",
            "Nº Telefone" => ""
        ),
    "1" => Array
        (
            "ID" => "8020",
            "Data" => "27/12/2017",
            "Horário" => "14:58:27",
            "Nº Telefone" => "1231530337"
        ),
    "2" => Array
        (
            "ID" => "8020",
            "Data" => "27/12/2017",
            "Horário" => "17:52:52",
            "Nº Telefone" => "1231530337"
        ),
    )

);


$values = array();
// construção dos values a serem inseridos na declaração insert
foreach ($array as $rowValues) {
  //se algum campo de um bloco for nulo, esse bloco não será salvo no banco
  $valido = false === array_search(false , $rowValues, false);
  if ($valido == true){
    $values[] = "(" ."'". implode('\',\' ', $rowValues) . "')";
  }
}
//declaração insert
$sql = "INSERT INTO ligacoes (cod,data,hora,telefone) VALUES " . implode (', ', $values);
$result = pg_query($sql); 

I adapted the array as shown in your question

  • Sorry for the delay in responding, I’m getting the following feedback INSERT INTO ligacoes (, , , ) VALUES ('8010',' 27/12/2017',' 14:58:27',' 1231530337'), ('8010',' 27/12/2017',' 14:56:52',' 1231530337'), ('8010',' 27/12/2017',' 10:53:14',' 11993229733'), ('8010',' 27/12/2017',' 10:44:05',' 11993229733'), ('8010',' 27/12/2017',' 08:01:37',' Anonymous') the $Fields field is returning empty, I tried to replace it with the name of my columns but it is not writing to the bank either, I created a test pag to check the INSERT in the BD and it is OK.

  • yes, I did this test by placing the values of the columns and also did not insert.

  • What are the column names?

  • You can post your form in the question?

  • Stayed like this $sql = "INSERT INTO ligacoes (cod, data, hora, telefone) VALUES " . implode (', ', $values);

  • I’m not using a form, this data comes from a table Jquery(Datatables) where I use the API Tabletojson and step to an AJAX ai where I send to PHP and now I’m trying to write in another BD

  • I just did a test here with column names in Insert and it worked too

  • But there is no way to be an array on the Insert page?

  • On the page I did test also worked $sql = "INSERT INTO ligacoes (cod, data, hora, telefone) VALUES (142, '01/402/2017', '401:02:03', '314523152')";&#xA;pg_query($conn, $sql);&#xA;pg_close($conn); this way inserted in BD, but when it is to pass the values automatically table does not insert.

  • If you can put the HTML in the question, I went

  • I’ll put, thank you for your help and my condolences.

  • @Diogomoura, unfortunately with what this posted in the question can not do tests

  • I will organize the Cod in the Pastebin and put the link here.

  • https://gist.github.com/diogom-42/4ed9c329acfe28bd948e7faf9a50a94b follows the link with the complete project code, thank you.

  • @Diogomoura, your database server is Postgresql, mine is Mysql, your project doesn’t work with me. But I did the following: I put your array directly in the test page and I went to the server (with Mysqli) and saved it in the database. Note that in the array 0 I put the names of the columns. I pastbin https://gist.github.com/anonymous/cd1bdf99646c93d888019f3f3bb625e9 The result was https://i.stack.Imgur.com/Jwcgq.png Repa

  • @Diogomoura, I took a look at my server and found that there is Postgresql Databases, I will try to create a database there !!!

  • thanks so much for the help, I’m here also doing some tests if I get something put here.

Show 12 more comments

Browser other questions tagged

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