Text as hyperlink SQL - php

I created a table in my database that has 3 columns on it, the third column is a Download File column that has a text on it that can redirect to a file in my uploads folder. Any ideas on how to create the file download column?
<script type="text/javascript">
var $table = $('#table');
$table.bootstrapTable({
url: 'list-user.php',
search: true,
pagination: true,
buttonsClass: 'primary',
showFooter: true,
minimumCountColumns: 2,
columns: [{
field: 'first',
title: 'Date',
sortable: true,
},{
field: 'last',
title: 'Title',
sortable: true,
}, {
field: 'file',
title: 'Download',
sortable: true,
}],
});
List-user file
<?php
require 'db.php';
$sqltran = mysqli_query($con, "SELECT * FROM user ")or die(mysqli_error($con));
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'num' => $i,
'first'=> $rowList['fname'],
'last'=> $rowList['lname']
);
array_push($arrVal, $name);
$i++;
}
echo json_encode($arrVal);
mysqli_close($con);
?>

You don't have an array key/value for your file column. Hard to know where you store the filename without seeing your database structure, but replace download_path_column_name with the correct column name.
$name = array(
'num' => $i,
'first'=> $rowList['fname'],
'last'=> $rowList['lname'],
'file' => 'Download'
);

Related

DataTables Server-side Processing: Joining two DB Column into One DT

I am new to DataTables Server Side Processing.
How can I join/combine two database column (db) in one datatables column (dt) using the server side script ? I tried:
$columns = array(
array( 'db' => 'id', 'dt' => 'id' ),
array( 'db' => array('firstname', 'lastname'),'dt' => 'priest' )
);
and it's NOT working. What is the right what to do that? Thank you!
I'm using DataTables-1.10.16.
You can also do it server side and then hide the column you don't want in js.
For example let's say you have a table with 3 columns: id, name and link.
To combine the link into the name do:
In html (header and footer) show both columns (we will hide the column dynamically in javascript):
<th>#</th><!--this is column 0 with id-->
<th>name</th><!--this is column 1 with name including a tag-->
<th>link</th><!--this is column 2 with link-->
In javascript:
$(document).ready(function() {
$('#table_id').DataTable(
"processing": true,
"serverSide": true,
"ajax": {
"url": "ajax.php"
},
"order": [[ 0, "asc" ]],//ordering by the id (usefull)
{"columnDefs": [
{ "visible": false, "targets": [ 0 ] },//hiding the id
{ "visible": false, "targets": [ 2 ] }//hiding the link column
]
});
});
In the ajax php script also describe both columns:
$columns = array(
array( 'db' => 'id', 'dt' => 0),
array(
'db' => 'name',
'dt' => 1,
'formatter' => function( $d, $row ) {
return ''.$d.'';
}
),
array( 'db' => 'link', 'dt' => 2 )
);
Sorry for late answer,
Actually in demo spss.php class you cannot merge them but we have a solution,
Which is using "Column Render"
Go to Server Side Processing file and
write a something like that (16 just assuming if you've 5 column u should write 6)
array( 'db' => 'database column', 'dt' => 16 )
Then go to the client;
$(document).ready(function() {
$('#example').DataTable( {
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
"render": function ( data, type, row ) {
return data +' ('+ row[16]+')';
},
"targets": 11
},
//This is makes db 16 row nonvisible
{ "visible": false, "targets": [ 16 ] }
],
} );
} );
"Targets":11 means i would like add something to 11. column.

Trying to create a dependent combobox in yii using ajax

I am trying to create a dependent combobox system in my Yii application.
First combobox is populated with States and the second one is dynamically generated with ajax and renderPartial() method.
Code below:
View
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
// Options passed to the text input
'htmlOptions' => array(
'style' => 'height: 36px',
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_name: state},
type: 'POST',
success: function (data) {
$('#city_id-carrier').html(data);
}
});
}
</script>
<div id="city_id-carrier" class="textboxes"></div>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_name']) ? $_POST['state_name'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$stateId = $state->id;
$cities = City::model()->findAllByAttributes(array(
'state_id' => $stateId
));
$this->renderPartial('_cities', array(
'cities' => $cities,
'stateId' => $stateId
), FALSE, TRUE
);
}
}
_cities.php
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => AdMulti::model(),
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData($cities, 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
// 'onSelect' => 'getLocalities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
The code is working and creating the combobox for the first time. But when I change the value in state combobox, something weird happens. A new combobox is created, but the values shown are still from the first combobox generated.
I am getting an error "TypeError: this.input is undefined" in Firebug Console.
I tried creating unique id for combobox using uniqid() but it isn't affecting the id of select element of the combobox.
If I change
$('#city_id-carrier').html(data)
to
$('#city_id-carrier').append(data)
it is working well but with multiple combobox generated.
Any ideas/suggestions to make this work?
I've found a solution to get this working. Instead of creating the combobox dynamically, place the combobox once and then populate it dynamically upon each request. Much like dependent dropdown.
A combobox is a combination of a dropdown and textbox. So, note down the id of the hidden dropdown and update it upon ajax update.
Code:
View:
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_id: state},
type: 'POST',
beforeSend: function() {
$('#AdMulti_city_id_combobox').val(''); // emptying textbox in case a value is previously selected.
},
success: function (data) {
$('#AdMulti_city_id').html(data); // populating the hidden dropdown.
}
});
}
</script>
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(array(''), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
'allowText' => false,
),
));
?>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_id']) ? $_POST['state_id'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$cities = City::model()->findAllByAttributes(array(
'state_id' => $state->id
));
$data = CHtml::listData($cities, 'id', 'name');
foreach ($data as $id => $name) {
echo CHtml::tag('option', array('value' => $id),
CHtml::encode($name), TRUE);
}
}
}

Custom MySQL query for jquery dataTables

the problem here is the dataTables pagination is not working
this is the script i created that outputs json from the database
include( "../database.php" );
$q = $dbh->prepare("SELECT r.studid, r.firstname, r.middlename, r.lastname, r.Enrolling, c.courseid,c.code, s.status,s.dateapproved,s.approvedby FROM pcc_registration r, pcc_courses c, pcc_studentsubj s WHERE c.courseid= r.Enrolling AND s.studentid=r.studid AND r.status=? AND s.status=? GROUP BY r.studid");
$q->execute(array(1,2));
$rows = array();
$i = 1;
while ($r = $q->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT, PDO::FETCH_COLUMN)){
$rows[] = array(
"DT_RowId" => "row_".$i,
"reg" => array(
"studid" => $r[0],
"firstname" => $r[1],
"middlename" => $r[2],
"lastname" => $r[3],
"course" => $r[6],
"dateapproved" => $r[8],
"approvedby" => $r[9]
),
);
$i++;
}
$rt = (STRING) $q->rowCount();
$data = array(
"draw" => 2,
"recordsTotal" => $rt,
"recordsFiltered" => $rt,
"data" => $rows
);
echo json_encode($data);
and this is the javascript that outputs the json encoded data to the page
(function($) {
$(document).ready(function() {
$('#dataTables-example').DataTable( {
processing: true,
serverSide: true,
ajax: {
url: "includes/php/approvedSched.php",
type: "POST"
},
"deferRender": true,
columns: [
{data: "reg.studid"},
{data: "reg.lastname"},
{data: "reg.firstname"},
{data: "reg.middlename"},
{data: "reg.course"},
{data: "reg.dateapproved"},
{data: "reg.approvedby"},
{data: "reg.studid"},
],
tableTools: {
sRowSelect: "os",
aButtons: [
// {sExtends: "editor_edit", editor: editor},
// {sExtends: "editor_remove", editor: editor}
]
}
} );
});
}(jQuery));
any answer or solution to this problem is appreciated =)
http://datatables.net/manual/server-side
http://coderexample.com/datatable-demo-server-side-in-phpmysql-and-ajax/
this links is a better help for custom server side with mySQL
Where is the problem exactly? Is it just the DataTable pagination, or is it related with the MySQL query? I mean, does it show the rows and the problem is just the pagination, or it doesn't show anything at all?
I had some issues 'transferring' the query result from php to js as JSON (I'm a complete web programming noob), but DataTables' pagination didn't gave me any problem...

How to filter with extra column in JSON PHP

I have a little statistic page where I can summorize my txt messages by user and by country.
I need now to have a new column where i can have operator as well.
To be more accurate, I need column to count all the Vodafone messages. I have already operator in my database and there are 5 different operators. I just need to bring out Vodafone.
Here are json php:
require_once("../corporate/php/modules/core/init.inc.php");
$where = " queue.dt_entered >= '".mysql_real_escape_string(trim($_POST["startdate"]))." 00:00:00' and queue.dt_entered <= '".mysql_real_escape_string(trim($_POST["enddate"]))." 23:59:59' ";
$result = $db -> query("
SELECT queue.user_id AS user, users.username as username, SUM( queue.amount ) AS amount, COUNT( queue.amount ) AS count, IFNULL( (
SELECT TRIM( country )
FROM CORE_E164
WHERE code = SUBSTR( queue.receiver, 3, 3 ) ) , IFNULL( (
SELECT TRIM( country )
FROM CORE_E164
WHERE code = SUBSTR( queue.receiver, 3, 2 ) ) , IFNULL( (
SELECT TRIM( country )
FROM CORE_E164
WHERE code = SUBSTR( queue.receiver, 3, 1 ) ) , 'None'
)
)
) AS country
FROM sms_queue AS queue, users AS users
WHERE queue.user_id = users.id
AND queue.client_type = 'corporative'
AND ".$where."
GROUP BY user, country
order by username
");
$result_array = array();
while ($row = mysql_fetch_array($result)) {
array_push($result_array, array("user" => $row["user"],
"username" => $row["username"],
"country" => $row["country"],
"amount" => $row["amount"],
"count" => $row["count"]
));
}
$result_total = array(
"success"=>true,
"messages" => $result_array
);
echo json_encode($result_total);
I am adding now the html page as well:
function columnWrap(val){
return '<div style="white-space:normal !important;">'+ val +'</div>';
}
var stat_store=new Ext.data.JsonStore({
root: 'messages',
fields : [
{name: 'id', mapping: 'user'},
{name: 'username', mapping: 'username'},
{name: 'country', mapping: 'country'},
{name: 'amount', mapping: 'amount'},
{name: 'count', mapping: 'count'},
{name: 'emt', mapping: 'emt'}
],
proxy : new Ext.data.HttpProxy({url:'group_stats.json.php'})
});
var filters = new Ext.ux.grid.GridFilters({
encode: false,
local: true,
filters: [{
type: 'string',
dataIndex: 'username'
},{
type: 'string',
dataIndex: 'country'
},{
type: 'string',
dataIndex: 'operator'
}]
});
var summary = new Ext.ux.grid.GridSummary();
var stat_grid = new Ext.grid.EditorGridPanel({
store: stat_store,
region: 'center',
plugins: [filters, summary],
columns: [
{header: "User ID", width: 50, dataIndex: 'id', sortable: true},
{header: "Username", width: 160, dataIndex: 'username', sortable: true, filterable: true},
{header: "Target country", width: 330, dataIndex: 'country', sortable: true, filterable: true},
{header: "Request count", width: 110, dataIndex: 'count', sortable: true, filterable: true, summaryType: 'sum'},
{header: "EMT count", width: 110, dataIndex: 'count', sortable: true, filterable: true, summaryType: 'sum'},
{header: "SMS sum", width: 110, dataIndex: 'amount', sortable: true, filterable: true, summaryType: 'sum'}
]
});
var FilterPanel = new Ext.FormPanel({
labelAlign: 'top',
frame:true,
region: 'north',
bodyStyle:'padding:5px 5px 0',
height: 95,
items: [{
layout:'column',
items:[{
columnWidth: 0.1,
layout: 'form',
items: [new Ext.form.DateField({
fieldLabel: 'Alguskuupäev',
name: 'startdate',
id: 'startdate',
value: new Date().format('Y-m-d'),
format:'Y-m-d',
anchor:'95%',
allowBlank:false })]
},{
columnWidth:.1,
layout: 'form',
items: [ new Ext.form.DateField({
fieldLabel: 'Lõppkuupäev',
name: 'enddate',
id: 'enddate',
value: new Date().format('Y-m-d'),
format:'Y-m-d',
anchor:'95%',
allowBlank:false })]
}]
}],
buttons: [{
text: 'Otsi',
handler: function(){
stat_store.baseParams = {startdate: Ext.get('startdate').dom.value, enddate: Ext.get('enddate').dom.value};
stat_store.load({params:{startdate: Ext.get('startdate').dom.value, enddate: Ext.get('enddate').dom.value}});
}
}]
});
var ContentPanel = new Ext.Panel({
layout: 'border',
items : [FilterPanel, stat_grid],
renderTo: 'list',
width: Ext.get('contentdiv').getWidth() - 5,
height: Ext.get('contentdiv').getHeight() - 30
});
Thank you,
Allan
So You want to count number of Vodafone messages among all selected messages.
SELECT ... SUM(IF(queue.operator = 'Vodafone', 1, 0)) AS vodafoners FROM ...
If You have access to some administration of the database (Adminer, phpMyAdmin or something similar), You can add the column in it. If You don't have such access, use SQL query to add the column:
ALTER TABLE yourTable ADD columnName columnType
For example:
ALTER TABLE sms_queue ADD opername VARCHAR(50)
And then use that column in Your SQL query:
... WHERE sms_queue.opername = 'Vodafone'
I also suggest using an index on that column.

flexigrid examples returning data from mysql

I'm sure it can be done, I just need to see some examples. I want to use flexigrid to show massive sets of data stored in mysql. I am proficient in php, but new to jquery and json.
Can anyone point me in the right direction or provide a good example? I need to see how to return data back to the flexigrid json.
Thank you
Great Tutorial on this topic
This is just the partial code for returning your database results, you would call you page with the flexigrid jquery code
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['pf_id'],
'cell' => array(
$row['cat_code'],
$row['cat_title'],
$row['cat_link'] = "Edit | Associate Familys | Order Children")); }
echo json_encode($data);
call the page with the flexigrid jquery code
$("#flex1").flexigrid({
url: 'category_main_json.php',
dataType: 'json',
colModel : [
{display: 'Code', name : 'cat_code', width : 70, sortable : true, align: 'left'},
{display: 'Name', name : 'cat_title', width : 550, sortable : true, align: 'left'},
{display: 'Action', name : 'cat_link', width : 205, sortable : true, align: 'left'},
],
buttons : [
{name: 'Add New Category', bclass: 'add', onpress : test},
{separator: true}
],
searchitems : [
{display: 'Code', name : 'cat_code'},
{display: 'Name', name : 'cat_title', isdefault: true}
],
sortname: "cat_code",
sortorder: "asc",
usepager: true,
useRp: true,
rp: 50,
showTableToggleBtn: false,
resizable: false,
width: 880,
height: 450,
singleSelect: true,
showTableToggleBtn: false
}
);

Categories