Domanda

I need to create dataTable from mysql database with google visualisation api. So i do this this:

try {

  $rez = $db->prepare("SELECT naziv FROM track_aktivnosti WHERE id_akt = :id_akt AND prvi=1 AND user_id=:user_id");
  $rez->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id));

  $kol = $rez->fetchAll();
  $rows = array();
  $rows1 = array();
  $table = array();
  $table = array();

  $rows[] = array('label' => 'Datum', 'type' => 'string');

  foreach ($kol as $r) {
    $rows[] = array('label' => (string) $r['naziv'], 'type' => 'string');
  }

  $table['cols'] = $rows;
  // convert data into JSON format
  $result = $db->prepare("SELECT datum FROM track_aktivnosti 
                                WHERE id_akt = :id_akt 
                                AND user_id=:user_id 
                                GROUP BY datum ORDER BY datum");

  $result->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id));
  $dates = $result->fetchAll();
  $final_result = array();

  $rows1 = array();
  foreach ($dates as $date) {

    $result = $db->prepare("SELECT vrednost, naziv 
                                    FROM track_aktivnosti 
                                    WHERE id_akt = :id_akt 
                                       AND datum = :datum  
                                       AND user_id= :user_id");

    $result->execute(array(':id_akt' => $_POST['id_akt'],
        ':datum' => $date['datum'],
        ':user_id' => $user_id));
    $m = array(array('v' => $date['datum']));
    foreach ($result as $r) {
      $m[] = array('v' => (int) $r['vrednost']);
    }
    $rows1[] = array('c' => $m);

    $table['rows'] = $rows1;
  }
} catch (PDOException $e) {
  echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($table);

So all is fine but this code change row values... as you can see from mysql database and in front end dataTable: so DataTable is: (for id_akt = 82) enter image description here

and mysql database is:

enter image description here

so as you can see in datatable i get for fdfdfd value 56 instead 76 and similar... How I can solve this?

UPDATE WITH JS CODE:

function drawTroskovnik() {
  var cssClassNames = {
    'headerRow': 'zaglavlje',
    'tableRow': 'red',
    'oddTableRow': 'red',
    'selectedTableRow': 'orange-background large-font',
    'hoverTableRow': 'prekoreda',
    'headerCell': 'gold-border',
    'tableCell': 'cell',
    'rowNumberCell': 'underline-blue-font'
  };

  // Create and populate the data table.
  var JSONObject = $.ajax({
    url: 'getTroskovnik.php', // make this url point to the data file
    dataType: 'json',
    data: {id_akt: ajdi},
    async: false,
    type: 'POST',
  }).responseText;

  var data = new google.visualization.DataTable(JSONObject, 0.5);

  for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
    for (var x = 1, maxcols = data.getNumberOfColumns(); x < maxcols; x++) {
      data.setValue(y, x, '<input vr="' + data.getValue(y, 0) + '" kol="' + data.getColumnLabel(x) + '" class="form-control costRedovi" value="' + data.getValue(y, x) + '">');
    }
  }
  for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
    data.setValue(y, 0, '<input class="span2 form-control" id="pocetak1" size="16" type="text" value="' + data.getValue(y, 0) + '" readonly>');
  }

  data.addColumn('string', '');
  for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
    var mc = data.getNumberOfColumns() - 1;
    data.setValue(y, mc, '<div data-toggle="tooltip" data-placement="top" title="Delete this day data"><i class="fa fa-trash-o" ></i></div>');
  }

  var table = new google.visualization.Table(document.getElementById('tpltroskovnik'));
  new google.visualization.events.addListener(table, 'ready', function() {
    $(".costRedovi").focusout(function() {
      var vrednost = $(this).val();
      var datum = $(this).attr('vr');
      var tabela = $(this).attr('kol');
      console.log(datum + " " + tabela + " " + vrednost);
      $.ajax({
        url: "updateCost.php",
        type: "POST",
        async: true,
        data: {ajdi: ajdi, datum: datum, tabela: tabela, vrednost: vrednost}, //your form data to post goes here as a json object
        dataType: "html",
        success: function(data) {
          console.log(data);
        },
      });
    });
  });

  table.draw(data, {'allowHtml': true, cssClassNames: {
      'headerRow': 'zaglavlje',
      'tableRow': 'red',
      'oddTableRow': 'red',
      'selectedTableRow': 'orange-background large-font',
      'hoverTableRow': 'prekoreda',
      'headerCell': 'gold-border',
      'tableCell': 'cell',
      'rowNumberCell': 'underline-blue-font'}
  });
};
È stato utile?

Soluzione

In the PHP code you provided there's no correlation between the column names and the row values. Therefore what values fall in which columns depends on the order the data is pulled from the database, which may be based on performance or insertion order, and can vary from one query to another. In order to have a predictable order, you need to specify in the query the order you want it pulled. The two queries that need to be aligned are: the one that pulls the names, and the one that pulls the values.

.

Lacking predictable ORDER:

$rez = $db->prepare("SELECT naziv FROM track_aktivnosti WHERE id_akt = :id_akt AND prvi=1 AND user_id=:user_id");

...

$result = $db->prepare("SELECT vrednost, naziv FROM track_aktivnosti WHERE id_akt = :id_akt AND datum = :datum AND user_id= :user_id");

.

Add ORDER BY naziv at the tail end of each of these to sort the results into a predictable alignment, which then gets properly loaded in your associative array, followed by the JSON object.

Here's a tweaked version of your code, cleaning up a few other non-critical issues:

<?php

try {

    $res = $db->prepare('SELECT naziv FROM track_aktivnosti WHERE id_akt = :id_akt AND user_id = :user_id AND prvi = 1 ORDER BY naziv');
    $res->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id));
    $kol = $res->fetchAll();

    $rows = array();
    $table = array();

    $rows[] = array('label' => 'Datum', 'type' => 'string');

    foreach ($kol as $r) {
        $rows[] = array('label' => (string) $r['naziv'], 'type' => 'string');
    }

    $table['cols'] =  $rows;

    $res = $db->prepare('SELECT datum FROM track_aktivnosti WHERE id_akt = :id_akt AND user_id = :user_id GROUP BY datum ORDER BY datum');
    $res->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id));
    $dates = $res->fetchAll();

    $rows = array();

    foreach($dates as $date){

       $res = $db->prepare('SELECT vrednost FROM track_aktivnosti WHERE id_akt = :id_akt AND user_id = :user_id AND datum = :datum  ORDER BY naziv');
       $res->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id, ':datum' => $date['datum']));
       $vals = $res->fetchAll();

       $m = array( array( 'v' => $date['datum'] ) );

       foreach($vals as $r) {
           $m[] = array('v' => (int) $r['vrednost']);
       }
       $rows[] =  array('c' => $m);

       $table['rows'] = $rows;
    }

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

echo json_encode($table);

?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top