2013-06-25 3 views
0

У меня есть база данных, состоящая из 4 столбцов (id-symbol-name-contractnumber). Все 4 столбца со своими данными отображаются в пользовательском интерфейсе с помощью JSON.Извлечение столбца базы данных с использованием JSON

Существует функция, которая реагирует на добавление нового столбца в базу данных, например (код страны).

coulmn успешно добавлен в базу данных, но не смог показать новый добавленный coulmn в пользовательском интерфейсе.

Ниже представлен мой код, отображающий столбцы.

Вы можете мне помочь?

Table.php

 <!DOCTYPE html> 
     <html lang="en"> 
     <head> 

<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" /> 
<script type="text/javascript" src="../../scripts/jquery-1.8.3.min.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxgrid.filter.js"></script>   
<script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script> 
<script type="text/javascript" src="../../jqwidgets/jqxlistbox.js"></script>  
<script type="text/javascript" src="../../jqwidgets/jqxdropdownlist.js"></script> 
<script type="text/javascript" src="../../scripts/gettheme.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
    // prepare the data 
    var theme = getDemoTheme(); 

    var source = 
    { 
     datatype: "json", 
    datafields: [ 
       { name: 'id' }, 
       { name: 'symbol' }, 
       { name: 'name' }, 

       { name: 'contractnumber' } 
      ], 
     url: 'data.php', 
     filter: function() 
     { 
      // update the grid and send a request to the server. 
      $("#jqxgrid").jqxGrid('updatebounddata', 'filter'); 
     }, 
     cache: false 
    };  
    var dataAdapter = new $.jqx.dataAdapter(source); 

    // initialize jqxGrid 
    $("#jqxgrid").jqxGrid(
    {  
     source: dataAdapter, 
     width: 670, 
     theme: theme, 
     showfilterrow: true, 
     filterable: true, 
     columns: [ 
      { text: 'id', datafield: 'id', width: 200 }, 
      { text: 'symbol', datafield: 'symbol', width: 200 }, 
      { text: 'name', datafield: 'name', width: 100 }, 
      { text: 'contractnumber', filtertype: 'list', datafield: 'contractnumber' } 
     ] 
    }); 
    }); 
</script> 
     </head> 
      <body class='default'> 
     <div id="jqxgrid"></div> 
     </div> 
      </body> 
     </html> 

data.php

 <?php 
#Include the db.php file 
include('db.php'); 
#Connect to the database 
//connection String 
$connect = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) 
or die('Could not connect: ' . mysql_error()); 
//Select The database 
$bool = mysql_select_db($mysql_database, $connect); 
if ($bool === False){ 
    print "can't find $database"; 
} 

$query = "SELECT * FROM pricelist"; 

$result = mysql_query($query) or die("SQL Error 1: " . mysql_error()); 
$orders = array(); 
// get data and store in a json array 
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
    $orders[] = array(
     'id' => $row['id'], 
     'symbol' => $row['symbol'], 
     'name' => $row['name'], 

     'contractnumber' => $row['contractnumber'] 

    ); 
} 

echo json_encode($orders); 
    ?> 

ответ

0

При добавлении нового столбца к вашей БД, вам придется как-то обновить пользовательский интерфейс, тоже. Для этого вам нужно будет добавить новое поле данных в массив полей данных исходного объекта и обновить столбцы Grid, установив свойство столбцов.

$ ("# jqxgrid"). JqxGrid ({columns: newColumnsArray});

+0

Можете ли вы мне посоветовать, как это сделать – arokia

0

Вы сказали, что столбец «contrycode» был правильно добавлен в таблицу pricelist? Таким образом, не очень сложно получить значения столбцов в $order и отобразить их как JSON. Не смотря на многое в вашем коде, я хотел бы начать с ...

# in your PHP 
$orders[] = array(
    'countrycode' = $row['countrycode'], 
    'id' => $row['id'], 
    ... 

и:

# in your JS 
    columns: [ 
     { text: 'countrycode', datafield: 'countrycode', width: 2 }, 
     { text: 'id', datafield: 'id', width: 200 }, 
    ... 
+0

Можете ли вы заглянуть в мой код. Coummn успешно добавлен в базу данных, но не смог показать новый добавленный coulmn в пользовательском интерфейсе. – arokia

0

Для стороны PHP это должно быть легко сделать массив для динамических полей, если вы используете цикл внутри время ,

$orders = array(); $i = 0; 
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
    $orders[$i] = array(); 
    foreach($row as $col => $value) { 
     $orders[$i][$col] = $value; 
    } 
    $i++; 
} 

Однако для jqgrid Вы должны найти решение для себя, чтобы показать динамические столбцы.

Смежные вопросы