Insert specific values from json to database with php - php

i have json data like this :
[
{
"id_user":"31",
"grade" : "A"
},
{
"id_user":"32",
"grade" : "A"
},
{
"id_user":"33",
"grade" : "B"
},
{
"id_user":"34",
"grade" : "B"
}
]
then i send the data with jquery
$.post("myaction.php",
{send: myjsondata }, function(res) {
}, "json");
then in myaction.php, i decode the json and i want to send the data to database
$conn = mysqli_connect( "localhost","root","","mydb");
$data = json_decode($_POST['send']);
foreach($data as $row){
$id_user = $row->id_user;
$grade = $row->grade;
mysqli_query($conn, "INSERT INTO tbl_user
(id_user,grade) VALUES ('$id_user','$grade') ");
}
but the problem is i want insert with id_user where the value is equal to grade A, how can i write the query?

You can check the grade's value in the for loop.
$grade = $row->grade;
if($grade == 'A'){
//proceed here.
}

Related

Insert JSON into Mysql problem (ajax/php)

I have a Json that I build after dropping a tab separated text into a text area (from this codepen example):
[
{
"0": "2019-08-31",
"1": "Bank Exp.",
"2": "EUR"
},
{
"0": "2019-08-31",
"1": "Legal",
"2": "EUR"
},
{
"0": "2019-08-31",
"1": "Legal",
"2": "EUR"
}
]
and is stored in variable:
jsonString = JSON.stringify(data, null, 2);
I then pass this json via ajax to a php file
var options = {
type: "POST",
url: "test.php",
data: { test: jsonString },
dataType: 'json',
success: function( data, status, xhr ) {
alert ("php:"+data);
},
error: function( xhr, status, error ) {
alert (data);
}
};
$.ajax( options );
to process a simple MYSQL insert of the different rows in the columns 0, 1, 2 in my 'test.php' file:
<?php
$host="localhost";
$user="renaud";
$pass="Mod100572$";
$db="accounting";
$con= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect to the database!!!");
$test = utf8_encode($_POST['test']);
$data_array = json_decode($test);
foreach($data_array as $row) {
$query .= "INSERT INTO `test` set
`field1` = '".$row['0']."',
`field2` = '".$row['1']."',
`field3` = '".$row["2"]."';";
}
if(mysqli_multi_query($con, $query)) {
$msg = "success";
} else {
$msg = "Something wrong! Please try again.";
}
mysqli_close($con);
?>
I Apparently do not achieve to convert my '$_POST['test']' into a correct array and the loop only gets '[' values. It is considered as a string, not an array.
I tried other parameters such as $data_array = json_decode($test,true); with no luck.
Any help to understand my error is deeply appreciated...
Insert syntax error
$query .= "INSERT INTOtestVALUES (
field1= '".$row['0']."',
field2= '".$row['1']."',
field3= '".$row["2"]."');";

Populate group data to a particular series on Highcharts

Trying to group tow columns and and populate it as a particular series on highcharts. my code not grouping columns, And showing all data as a single series.
$query = $db->Prepare("SELECT class, SUM(marks), DATE(date_column) as
dates FROM classes GROUP BY class,DATE(date_column)");
$query->execute();
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$date = $row['dates'];
$dates[] = $row['dates'];
$class[] = $row['class'];
$marks[] = $row['SUM(marks)'];
$output[] = array($date,(int)$marks);
}
echo json_encode(array('date'=>$dates,'marks'=>$marks, 'name' => $class));
JS
<script>
$(document).ready(function () {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.dates
},
series : [{
"name" : data.name,
"data": data.marks
}],
});
});
});
});
</script>
Table
Expected output in JSFiddle
data response
date: ["2019-02-07", "2019-02-09", "2019-02-12", "2019-02-08", "2019-02-12",
"2019-02-13", "2019-03-13",…]
marks: ["45", "166", "78", "64", "64", "627", "87", "352"]
name: ["claas 1", "claas 1", "claas 1", "class 2", "class 2", "class 2", "class 3", "class 3"]
By seeing your fiddle the expected output you want for HighCharts is as follow:
1: Category Data:
It should be an array of dates.
Make sure you remove duplicates and order them in ascending/descending order whichever you want, to see a continuous graph.
"categories":["2019-02-07", "2019-02-08", "2019-02-09", "2019-02-12", "2019-02-13", "2019-02-14"]
2: Series Data:
It would be an array of object, where each object contains two properties name and data.
Data should have n no of values if your categories array has n values and each corresponds to same index.
As we don't have data for each date for each class, we would add 0 there.
So data would look like
"series":[
{
"name":"class 1",
"data":[45,0,166,78,0,0]
},
{
"name":"class 2",
"data":[0,64,0,64,627,0]
},
{
"name":"class 3",
"data":[0,0,0,0,87,352]
}
]
Final Fiddle which can be achieved by PHP using below code:
$arrDates = [];
$arrClass = [];
$arrData = [];
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$arrDates[] = $row['dates'];
$arrClass[] = $row['class'];
$arrData[$row['class'] . ':' . $row['dates']] = $row['marks']; // to identify for which date & class this marks belong to, we can directly search for index.
}
$arrDates = array_unique($arrDates);
sort($arrDates);
$arrClass = array_unique($arrClass);
// Create series data
$arrSeriesData = [];
foreach($arrClass as $strClass){
$tempArr = ['name' => $strClass];
foreach($arrDates as $strDate){
$tempArr['data'][] = isset($arrData[$strClass . ':' . $strDate]) ? intval($arrData[$strClass . ':' . $strDate]) : 0;
}
$arrSeriesData[] = $tempArr;
}
$response = ['categories' => $arrDates, 'series' => $arrSeriesData];
echo json_encode($response);
Output:
{"categories":["2019-02-07","2019-02-08","2019-02-09","2019-02-12","2019-02-13","2019-02-14"],"series":[{"name":"class 1","data":[45,0,166,78,0,0]},{"name":"class 2","data":[0,64,0,64,627,0]},{"name":"class 3","data":[0,0,0,0,87,352]}]}
Update your javascript code to reflect the above
$(document).ready(function() {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.categories
},
series: data.series,
});
});
});
});

Send POST parameters to PHP in ajax call of jQuery datatable

I want to make a jQuery function in where, getting a value of an input, send it to a PHP file to make a query in mysql and populate a datatable with the information received.
Another problem I have is that the table is initialized when the user is logged in and I don't know if that can obstruct the function I want to do.
This the table:
Table and button
This is where I initialize it:
$.fn.dataTable.ext.errMode = 'none';
var table = $('#m3_sem').DataTable( {
"ajax": "dist/ajax/prueba_m3_sem.php",
"paging": false,
"ordering": false,
"info": false,
"searching": false,
"columns": [
{ "data": "resistencia" },
{ "data": "res1" },
{ "data": "res2" },
{ "data": "res3" },
{ "data": "res4" },
{ "data": "res5" },
{ "data": "res6" },
{ "data": "total" }
],
"order": [[0, 'asc']],
"pagingType": "full_numbers",
"language": {
"sSearch" : "Buscar:",
"lengthMenu": "Mostrando _MENU_ registros por pagina",
"zeroRecords": "No hay pedidos pendientes",
"info": "Mostrando pagina _PAGE_ de _PAGES_",
"infoEmpty": "Sin registros",
"infoFiltered": "(Filtrados de _MAX_ registros totales)",
"paginate" : {
"first" : "Primera pagina",
"previous" : "Anterior",
"next" : "Siguiente",
"last" : "Ultima pagina"
}
}
});
} );
And this is the PHP file "prueba_m3_sem.php", it generates the JSON I use to populate the table:
$sql = "SELECT DISTINCT resistencia ";
$sql.= "FROM registros ORDER BY resistencia";
$query=mysqli_query($conexion, $sql) or die("ajax-grid-data.php: get PO");
$data = array();
while( $row=mysqli_fetch_array($query) ) {
$sumtot = 0;
$nestedData=array();
$nestedData["resistencia"] = $row["resistencia"];
$sqld = "SELECT DISTINCT(fecha_entrega) FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
$queryd=mysqli_query($conexion, $sqld) or die("ajax-grid-data.php: get PO");
$count = 0;
$tot = 0;
while( $rowd=mysqli_fetch_array($queryd) ) {
$count++;
$m3tot = 0;
$sqlm = "SELECT m3 FROM registros WHERE fecha_entrega = '".$rowd["fecha_entrega"]."' AND resistencia =".$row["resistencia"]."";
$querym=mysqli_query($conexion, $sqlm) or die("ajax-grid-data.php: get PO");
while( $rowm=mysqli_fetch_array($querym) ) {
if (empty($rowm['m3'])){
$m3 = 0;
}else{
$m3 = $rowm["m3"];
}
$m3tot = $m3tot + $m3;
}
$tot = $tot + $m3tot;
$nestedData["res".$count] = $m3tot;
$sumtot = $sumtot + $m3tot;
}
$nestedData["total"] = "<b>".$sumtot."</b>";
$data[] = $nestedData;
}
$sqld2 = "SELECT DISTINCT(fecha_entrega) as fecha FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
//echo $sqld;
$queryd2=mysqli_query($conexion, $sqld2) or die("ajax-grid-data.php: get PO");
$totm3 = 0;
$nestedData["resistencia"] = "<b>Total</b>";
$count = 0;
while( $rowd2=mysqli_fetch_array($queryd2) ) {
//echo $rowd["fecha"]."</br>";
$sqltot = "SELECT SUM(m3) AS m3 from registros WHERE fecha_entrega ='".$rowd2["fecha"]."'";
$querytot=mysqli_query($conexion, $sqltot) or die("ajax-grid-data.php: get PO");
while( $rowtot=mysqli_fetch_array($querytot) ){
$count ++;
//echo $rowtot["m3"]."</br>"
$nestedData["res".$count] = "<b>".$rowtot["m3"]."</b>";
$totm3 = $totm3 + $rowtot["m3"];
}
}
$nestedData["total"] = "<b>".$totm3."</b>";
$data[] = $nestedData;
$json_data = array("data" => $data);
echo json_encode($json_data);
I've seen some code examples and the datatable documentation but I just can't find something that fits in the function I need or I just don't understand it very well.
Also, as you can see, English is not my native language. I hope and you can forgive my misspellings.
In advance thanks a lot for your response.
what I understand is that you want to display some results in your table after you submit some search value? if thats the case here is a little example I did using a employees sample db with mysql:
the html:
<div class="container">
<input type="text" name="txtName" id="txtName" value="">
<button type="btn btn-default" name="button" id="btnSearch">Search</button>
</div>
<div class="container" id="tblResult" style="display:none;">
<div class="row">
<div class="col-sm-6">
<table id="example" class="table table-responsive" style="width:100%">
<thead>
<tr>
<th>Cliente</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Device Id.</th>
<th>Client id</th>
<th>Accion</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Cliente</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Device Id.</th>
<th>Client id</th>
<th>Accion</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
I use an input to search employees by a name parameter in this example so if you want to filter by a date it would not be that different.
the javascript:
$(document).ready(function(){
// click event to call the datatable request
$('#btnSearch').on('click', (event) => {
let search = $('#txtName').val();// get the input value
if (search != "") {// validate that the value is not empty
//assing the datatable call to a variable
let example = $('#example').DataTable({
"destroy": true,
"responsive":{//this is usefull if you want to use a full responsive datatable just add the responsive css from dataTables.net
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,//
"ajax": {
"url": 'request.php',
"method": 'POST',
data:{action:"SLC",name:search}//parameter to search and the action to perform
},
"columns": [
{"data": "emp_no"},
{"data": "first_name"},
{"data": "last_name"},
{"data": "gender"},
{"data": "salary"},
{"data": "title"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},//load all dataTables default values in spanish
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});//fin obtener tabla
example.on( 'xhr', function ( e, settings, json ) {// check is the response is not null and show the table
if (json != null) {
$('#tblResult').css("display","");
}
} );
}
});
}); //end ready
As you can see I call the dataTable method until a search is performed also I display the Table if the response is not empty.
the php:
<?php
$host = '127.0.0.1';
$db = 'employees';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$pdo = "";
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// a fucntion that display the employees by our search value
function getEmployeesBySearch($conn,$order,$name) {
$sql = "SELECT e.emp_no,e.first_name,e.last_name,e.gender, gs.salary, gt.title
FROM employees e
inner join (
SELECT s.emp_no,MAX(s.salary) AS salary
FROM salaries s
GROUP by s.emp_no
) as gs on e.emp_no = gs.emp_no
inner join (
SELECT t.emp_no ,t.title ,MAX(t.from_date) as from_date
FROM titles t
WHERE t.to_date = '9999-01-01'
GROUP BY t.emp_no,t.title
) gt on e.emp_no = gt.emp_no
WHERE gt.title = 'Senior Engineer'
AND e.emp_no BETWEEN 10001 and 11819";
//use bind parameters and prepared statement to do the search and prevent sql injection
if ($name != "") {
$sql .= " AND e.first_name like CONCAT( '%', :name, '%')";
}
if ($order == "DESC") {
$sql .= " ORDER BY gs.salary DESC";
}else {
$sql .= " ORDER BY gs.salary ASC";
}
$json= array();
$stmt = $conn->prepare($sql);
if ($name != "") {
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 100);
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$rows = $stmt->fetchAll();
//store the data inside an array
foreach ($rows as $row) {
$tempArray = array(
'emp_no'=>$row["emp_no"],
'first_name'=>$row['first_name'] ,
'last_name'=>$row['last_name'],
'gender'=>$row['gender'],
'salary'=>$row['salary'],
'title'=>$row['title']
);
//json encode the array and send the response back
$json["data"][] = $tempArray;
}
echo json_encode($json);
}
if (isset($_POST["action"])) {
// we set the variables here, since you will add another stuff later I decided a switch to run a specific case with the action the user send
$action = $_POST["action"];
$order = (isset($_POST["order"]) ? $_POST["order"] : "");
$name = (isset($_POST["name"]) ? $_POST["name"] : "");
switch ($action) {
case 'SLC':
getEmployeesBySearch($pdo,$order,$name);
break;
}
}
?>
I use a simple connection here and a function that load the results from my db to send them back as a json rsponse also try to use prepared statements in your querys and bind parameters like the example
Hope it helps =)

php sum array values in loop and push the final value into array

I have a piece of code which needs to fetch values from stored procedure, using loop have to sum the result values and finally push into an array for json generation,
my code,
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XXXX","XXX","XXXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$response["Details"] = array();
while(($row = mysqli_fetch_array($query)))
{
$value = array();
$tot_files= $row["Totfiles"];
$value["Totfiles"] +=$tot_files; //final sum value of "Totfiles"
$tot_file_mins= $row["file_minutes"];
$value["file_minutes"] +=$tot_file_mins; //final sum value of "file_minutes"
array_push($response["Details"], $value);
}
echo json_encode($response);
?>
output what am getting now,
{
"Details":[
{
"Totfiles":55,
"file_minutes":125
},
{
"Totfiles":60,
"file_minutes":82
},
{
"Totfiles":7,
"file_minutes":75
},
{
"Totfiles":8,
"file_minutes":108
},
{
"Totfiles":9,
"file_minutes":12
},
{
"Totfiles":7,
"file_minutes":11
},
{
"Totfiles":13,
"file_minutes":30
},
{
"Totfiles":12,
"file_minutes":28
},
{
"Totfiles":8,
"file_minutes":15
},
{
"Totfiles":3,
"file_minutes":4
},
{
"Totfiles":4,
"file_minutes":6
},
{
"Totfiles":1,
"file_minutes":1
},
{
"Totfiles":3,
"file_minutes":6
},
{
"Totfiles":2,
"file_minutes":4
},
{
"Totfiles":64,
"file_minutes":339
},
{
"Totfiles":24,
"file_minutes":96
},
{
"Totfiles":3,
"file_minutes":6
},
{
"Totfiles":19,
"file_minutes":48
},
{
"Totfiles":2,
"file_minutes":10
},
{
"Totfiles":1,
"file_minutes":2
},
{
"Totfiles":7,
"file_minutes":32
},
{
"Totfiles":4,
"file_minutes":16
}
]
}
my desired output,
{"Details":[{"Totfiles":695,"file_minutes":365}]}
Thanks in advance
try this:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XXXX","XXX","XXXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$response["Details"] = array();
$Totfiles = 0;
$file_minutes = 0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"]; //final sum value of "Totfiles"
$file_minutes +=$row["file_minutes"]; //final sum value of "file_minutes"
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
echo json_encode($response);
?>
I have not tested this code but hope that this should work.
Just adding values inside the loop and then push values to array after finishing the loop.
$totalfile=0;
$totalmin=0;
while(($row = mysqli_fetch_array($query)))
$value = array();
$tot_files= $row["Totfiles"];
$totalfile +=$tot_files; //final sum value of "Totfiles"
$tot_file_mins= $row["file_minutes"];
$totalmin +=$tot_file_mins; //final sum value of "file_minutes"
}
$response["Details"]["Totfiles"]=$totalfile;
$response["Details"]["file_minutes"]=$totalmin;
echo json_encode($response);

Do I need a 2nd database to manage my PHP form, which provides users access to data from a large existing database?

I am trying to create an application (basically just a form) using PHP to help users query an existing large MySQL database that is used to store test results. The plan has been to have a powerful server query and process data from the existing database and send reports about that data to the application to be displayed.
The existing database might be utilized for new types of test data, so the form must be able to change based on the new data types. It would also be great to be able to have sort of an administration panel for the application that could configure what options are available on the form for users to select, based on user requests. I don't really want to go so far as managing users accounts of this application, I want it to be generic.
It seems that it would be logical for me to create MySQL tables to manage the form. Is this wrong? Should tables that manage the application for accessing the large database exist in the large database itself, rather than creating a database specifically for the interfacing PHP application?
Form Generation:
<?php
$dbhost = "";
$dbuser = "";
$dbpassword = "";
$dbname = "";
$dbport = "";
//*/
//Data types lookup table: Array of short names each with 2nd dimension array
//containing table name in database, Human Name
$url = $_SERVER['QUERY_STRING'];
$data = array
(//$type $name[0] = table name $name[1] = Readable name
//key, short name?
//Lookup table (parameter/form enable/disable? database?)
'tbl1'=>array('table1_data_tbl1', ''
),
'tbl2'=>array('table2_data_tbl2', ''
),
'tbl3'=>array('table3_data_tbl3', ''
),
'tbl4'=>array('table4_data_tbl4', ''
),
'tbl5'=>array('table5_data_tbl5', ''
),
'tbl6'=>array('table6_data__tbl6', ''
)
);
error_reporting(E_ALL);
//I COPIED THIS CODE
//-copied-Creates two dimensional array ($params) containing $_GET data, creating an
//-copied-array for each unique $_GET parameter containing their values.
if(isset($_GET["run"])||isset($_GET["data"])){
$query = explode('&', $_SERVER['QUERY_STRING']);
$params = array();
foreach( $query as $param )
{
list($name, $value) = explode('=', $param);
$params[urldecode($name)][] = urldecode($value);
}
//If the run has been selected: create region query, update url variable.
if(isset($_GET["run"])){
$id_run_rgn_query = implode(" OR id_run_rgn = ",$params["run"]);
$id_run_PARAM1_query = implode(" OR id_run_PARAM1 = ",$params["run"]);
$id_run_url = implode("&run=",$params["run"]);
}
//If data type has been selected: create run query?, update url variable.
if(isset($_GET["data"])){
$id_run_tbl4_query = implode(" OR id_run_tbl4 = ",$params["data"]);
$id_run_tbl5_query = implode(" OR id_run_tbl5 = ",$params["data"]);
$id_run_tbl3_query = implode(" OR id_run_tbl3 = ",$params["data"]);
$id_run_tbl6_query = implode(" OR id_run_tbl4 = ",$params["data"]);
$id_run_tbl2_query = implode(" OR id_run_tbl4 = ",$params["data"]);
$id_data_url = implode("&data=",$params["data"]);
}
if(isset($_GET["data"])){
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript" src="view.js"></script>
<script src="jquery.js"></script>
<script src="addInput.js"></script>
<script src="jquery.dform.js"></script>
</head>
<body id="main_body" >
<?php
$db=mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname,$dbport);
if (!$db)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
?>
<img id="top" src="form/top.png" alt=""/>
<div id="form_container">
<h1><a></a></h1>
<div class="form_description">
<h2></h2>
<p>Retrieve testing data from database.</p>
</div>
<form id="myform">
<script type="text/javascript">
var phpurl = "<?php echo $url; ?>";
$(function() {
// Generate a form
$("#myform").dform({
"action" : "createquery.php",
"method" : "get",
"target" : "blank",
"html" :
[
{
"name" : "data",
"id" : "data",
"caption" : "Select category of data:<br>",
"type" : "select",
"options" : {
<?php
//$data = ['tbl3','tbl4','tbl5','table1_cw','dist','tbl6','tbl2'];
$i=0;//increment for selected datatypes
$j=1;//increment for number of datatypes, used to omit final comma
foreach ($data as $type => $name){
echo '"'.$type.'" : ';
if(isset($params["data"][$i]) && ($params["data"][$i] == $type)){
echo '{';
echo '"selected" : "selected",';
echo '"html" : "'.$name[1].'"';
echo '}';
$i++;
}
else{
echo '"'.$name[1].'"';
}
if(sizeof($data)!=$j++){
echo ',';
//Formatting, PHP does not allow escape chars in single quotes
echo "\n ";
}
}
echo "\n";
?>
},
"size" : <?php echo sizeof($data);?>,
"multiple" : "multiple"
},
{
"type" : "br"
}
<?php
//List experiment runs available if data is selected
if(isset($params["data"][0])){?>
,{
"name" : "run",
"id" : "run",
"caption" : "Select experiments:<br>",
"type" : "select",
"options" : {
<?php
// $totalruns is value returned from query:
// SELECT COUNT(id_run) FROM run_run;
$totalruns=291;
$i=0;
$j=0;
$distinct = array();
$numdata = sizeof($params["data"]);
foreach ($data as $type => $name){
if(in_array($type,$params["data"]) && sizeof($distinct) < $totalruns){
$j++;
$sql = "SELECT DISTINCT id_run_".$type.
" FROM ".$name[0];
$rs_result = mysqli_query ($db,$sql);
$temp_distinct = array();
$num_run = mysqli_num_rows($rs_result);
//Only get results if less than total runs
if($num_run <= $totalruns){
while( $row = mysqli_fetch_array( $rs_result)){
$temp_distinct[] = $row['id_run_'.$type]; // Inside while loop
}
$distinct = array_unique(array_merge($temp_distinct,$distinct));
}
//If the data type is involved in EVERY run, nothing is distinct
else {$distinct = "";break;}
$i++;
if($i==$numdata){break;}
//if(sizeof($distinct) >= $totalruns){
// break;
//}
}
}
if($distinct!=""){
$distinctquery = implode(" OR id_run = ",$distinct);
}
else{
$distinctquery = "";
}
//*Verify it's working:
echo '"777" : "Queries Performed: '.$i.'",';
echo '"778" : "Loops before break: '.$j.'",';
echo '"779" : "dataparam: '.$params["data"][0].'",';
echo '"780" : "Size: '.sizeof($distinct).'",';
//foreach($params["data"] as $)
$sql = "SELECT id_run,experiment_run FROM run_run";
//"FROM run_run" .
if(!empty($distinctquery)){$sql=$sql." WHERE id_run = ".$distinctquery;}
" ORDER BY id_run ASC";
$rs_result1 = mysqli_query ($db,$sql);
$num_run = mysqli_num_rows($rs_result1);
//echo '"num_run" : "'.$num_run.'",';
$i=0;
$j=1;
while ($row = mysqli_fetch_array($rs_result1)) {
echo '"'.$row["id_run"].'" : ';
if(isset($params["run"][$i]) && ($params["run"][$i] == $row["id_run"])){
echo '{';
echo '"selected" : "selected",';
echo '"html" : "'.$row["experiment_run"].'"';
echo '}';
$i++;
}
else{
echo '"'.$row["experiment_run"].'"';
}
if($num_run!=$j++){
echo ',';
}
}
mysqli_close($db);
?>
},
"size" : 7,
"multiple" : "multiple"
}
<?php
}//endbracket for data isset check
echo "]});";
if(isset($_GET["run"])){?>
$("#myform").append('<table id="myTable"><tr><th>Parameter</th><th>Filter</th><th>Usage</th></tr>');//\n\
$("#myTable tr:last").after("<tr><td>Param 1 Name</td><td>");
$("#myTable td:last").dform({
"html" :
[
{
"type" : "checkbox",
"name" : "pePARAM1",
"id" : "pePARAM1",
"value" : "0",
"caption" : ""
<?php if(isset($_GET['pePARAM1'])){echo ',"checked" : ""';}?>
}
]
});
$("#myTable td:last").after("</td><td>");
$("#myTable td:last").dform({
//"html" :
//[
//{
"name" : "poPARAM1",
"id" : "poPARAM1",
"caption" : "",//</td><td>",
"type" : "select",
"options" :
{
"xprm" : "X axis",
"yprm" : "Y axis",
"avg" : "AVERAGE",
"grp" : "GROUP BY"
},
"size" : "1"
//"disabled" : ""
});
//Parameter Entry 2
$("#myTable tr:last").after("<tr><td>Param 2 Name</td><td>");
$("#myTable td:last").dform({
"html" :
[
{
"type" : "checkbox",
"name" : "pePARAM2",
"id" : "pePARAM2",
"value" : "0",
"caption" : ""
<?php if(isset($_GET['pePARAM2'])){echo ',"checked" : ""';}?>
}
]
});
$("#myTable td:last").after("</td><td>");
$("#myTable td:last").dform({
//"html" :
//[
//{
"name" : "poPARAM2",
"id" : "poPARAM2",
"caption" : "",//</td><td>",
"type" : "select",
"options" :
{
"xprm" : "X axis",
"yprm" : "Y axis",
"avg" : "AVERAGE",
"grp" : "GROUP BY"
},
"size" : "1"
//"disabled" : ""
});
//End of Parameter Select List
$("#myTable td:last").after("</td></tr></table>");
$("#myform").dform({
"html" :
[
{"type":"br"
//"caption":"</td></tr></table>"
},
<?php
//Parameter 1 Form
if(isset($_GET["pePARAM1"])){
?>
{
"type" : "div",
"class" : "pePARAM1",
"html" :
[
{
"type" : "select",
"name" : "PARAM1",
"id" : "PARAM1",
//"class" : "PARAM1"
"caption" : "Select Param 1 Name<br>",
"options" : {
<?php
$db=mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname,$dbport);
if (!$db)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$sql = "SELECT id_PARAM1,subparam1_PARAM1,subparam2_PARAM1
FROM PARAM1_PARAM1
WHERE id_run_PARAM1 = ".$id_run_PARAM1_query
." ORDER BY subparam1_PARAM1 ASC";
$rs_result = mysqli_query ($db,$sql);
$num_PARAM1 = mysqli_num_rows($rs_result);
$i=1;
while ($row = mysqli_fetch_array($rs_result)) {
echo '"'.$row["id_PARAM1"].'" : ';
echo '"Param 1 Name '.$row["id_PARAM1"].', Parameter of Param '.$row["subparam_PARAM1"].', Another Sub Parameter'.$row["subparam_PARAM1"].'"';
if($num_PARAM1!=$i++){
echo ',';
}
}
mysqli_close($db);
?>
},
"size" : 7,
"multiple" : "multiple",
"disabled" : "false"
}
]
},
<?php }
//Parameter 2 Form
if(isset($_GET["pePARAM2"])){
?>
{
"type" : "div",
"class" : "pePARAM2",
"html" :
[
{
"type" : "checkbox",
"id" : "element0",
"value" : "element0",
"caption" : "0"
},
{"type":"br"},
{
"type" : "select",
"name" : "region",
"id" : "region",
"caption" : "Select Region<br>",
"options" : {
<?php
$db=mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname,$dbport);
if (!$db)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$sql = "SELECT id_rgn,id_param1_rgn,param2_rgn
FROM region_rgn
WHERE id_run_rgn = ".$id_run_rgn_query."
ORDER BY id_rgn ASC";
$rs_result1 = mysqli_query ($db,$sql);
$num_rgn = mysqli_num_rows($rs_result1);
$i=1;
while ($row = mysqli_fetch_array($rs_result1)) {
echo '"'.$row["id_rgn"].'" : ';
echo '"Param 1 Name '.$row["id_param1_rgn"].', Param 2 Name '.$row["param2_rgn"].'"';
if($num_rgn!=$i++){
echo ',';
}
}
mysqli_close($db);
?>
},
"size" : 7,
"multiple" : "multiple"
}
]
},
<?php }?>
{
"type" : "submit",
"id" : "submit",
"value" : "Get Data"
}
]
});
<?php }?>
});
</script>
<script>
var url = '';
$( document ).ready(function() {
$( "#data").click(function( event ) {
var selectedValues = [];
$("#data :selected").each(function(){
selectedValues.push($(this).val());
});
selectedValuesUrl = selectedValues.join('&data=');
window.location.href = "createqueryform.php?data=" + selectedValuesUrl;//"data=tbl4&run=7";//<?php //echo "data=tbl4&run=7"; ?>;
event.preventDefault();
});
$( "#run").click(function( event ) {
var selectedValues = [];
$("#run :selected").each(function(){
selectedValues.push($(this).val());
});
selectedValuesUrl = "&run=" + selectedValues.join('&run=');
window.location.href = "createqueryform.php?" + phpurl + selectedValuesUrl;//"data=tbl4&run=7";//<?php //echo "data=tbl4&run=7"; ?>;
event.preventDefault();
});
$( "#pePARAM1, #pePARAM2").click(function( event ) {
//var phpurl = "<?php //echo $url; ?>";
var param = $(this).attr('id');
var flag = "&" + param + "=1";
if ($(this).is(":checked")){
window.location.href = "createqueryform.php?" + phpurl + flag;
}
else
{
phpurl = phpurl.replace(flag,'');
var div = '.' + param;
$(div).remove();
}
});
});
</script>
_Note: I've replaced (messily) table names with generic names in an attempt to disguise the type of test data I'm working with, and the code is probably pretty horrible. This code is very unfinished. I'm still deciding on form objects I want to use for people to generate queries. The original question is referring to whether I should have a database (separate from the one I'm querying using this form) that can manage the form objects available for users, and to help expand types of data available.
Id make a table for each form element: category, experiments, param, region, etc in the existing database. There is no need for another database, unless it completely unrelated data, from a completely unrelated app.
Or make just one table called: 'testing_options' in the same database where the form elements share one column named 'key' that saves the type of element it is (category, experiments, param, region), and their value in a column named 'value'. Thus a key/value table to serve the form options.

Categories