<?php
require_once("includes/initialize.php");
global $database;

$column = array('formno', 'surname', 'othernames', 'courses', 'programme', 'session', 'reg_date');

$query = "SELECT formno,surname,othernames,courses,programme,session,reg_date FROM admitted_student_details ";

if(isset($_POST['search']['value']))
{
 $query .= '
 WHERE formno LIKE "%'.$_POST['search']['value'].'%" 
 OR surname LIKE "%'.$_POST['search']['value'].'%" 
 OR othernames LIKE "%'.$_POST['search']['value'].'%" 
 OR courses LIKE "%'.$_POST['search']['value'].'%" 
 OR programme LIKE "%'.$_POST['search']['value'].'%"
 OR session LIKE "%'.$_POST['search']['value'].'%"
 OR reg_date LIKE "%'.$_POST['search']['value'].'%" 
 ';
}

if(isset($_POST['order']))
{
 $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY CustomerID DESC ';
}

$query1 = '';

if($_POST['length'] != -1)
{
 $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

// $sql = mysql_query($query);
$statement = $database->prepare($query);

$statement->execute();
// $rows= mysql_fetch_array($sql);
$number_filter_row = $statement->rowCount();
// $number_filter_row = $rows->rowCount();

$statement = $database->prepare($query . $query1);
// $sql = mysql_query($query.$query1);
$statement->execute();
// $rows= mysql_fetch_array($sql);
$result = $statement->fetchAll();

$data = array();

foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row['formno'];
 $sub_array[] = $row['surname'];
 $sub_array[] = $row['othernames'];
 $sub_array[] = $row['courses'];
 $sub_array[] = $row['programme'];
 $sub_array[] = $row['session'];
 $sub_array[] = $row['reg_date'];
 $data[] = $sub_array;
}

function count_all_data()
{
 $query = "SELECT formno,surname,othernames,courses,programme,session,reg_date FROM admitted_student_details";
//  $sql = mysql_query($query);
// $rows= mysql_fetch_array($sql);

 $statement = $database->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

$output = array(
 'draw'    => intval($_POST['draw']),
 'recordsTotal'  => count_all_data(),
 'recordsFiltered' => $number_filter_row,
 'data'    => $data
);
echo $output;
echo json_encode($output);

?>
