Search Datatables in serverside mode

Asked

Viewed 37 times

0

I’m about to finish a project and still need to improve the Datatables research. Use serverside mode and ajax search is this:

<?php
	/******* Conexão com o bando de dados *******/
	include "../../Conexao/config.php";
	mysqli_select_db($config, $database_config);
	mysqli_set_charset($config,"utf8");
	/******* Conexão com o bando de dados *******/

	// storing  request (ie, get/post) global array to a variable  
	$requestData= $_REQUEST;

	$columns = array( 
		// datatable column index  => database column name
		0 => 'id',
		1 => 'data_criacao', 
		2 => 'razao_social',
		3 => 'Nome do Usuário',
		4 => 'categoria',
		5 => 'cidade',
		6 => 'uf',
		7 => 'status'	
	);

	$table  = "tb_empresas";
	$campos = "id, data_criacao, razao_social, CodCli, categoria_base, cidade, uf, status";

	// getting total number records without any search
	$sql           = "SELECT $campos ";
	$sql.=" FROM $table";
	$query         = mysqli_query($config, $sql) or die(mysqli_error($config));
	$totalData     = mysqli_num_rows($query);
	$totalFiltered = $totalData;  // when there is no search parameter then total number rows = total number filtered rows.

	$sql           = "SELECT $campos ";
	$sql.=" FROM $table WHERE 1=1";
	if(!empty($requestData['search']['value']) ) {   
		// if there is a search parameter, $requestData['search']['value'] contains search parameter
		$sql.=" AND ( id LIKE '".$requestData['search']['value']."%' "; 
		$sql.=" OR data_criacao LIKE '".$requestData['search']['value']."%' ";    
		$sql.=" OR razao_social LIKE '".$requestData['search']['value']."%' ";
		$sql.=" OR CodCli LIKE '".$requestData['search']['value']."%' ";
		$sql.=" OR categoria_base LIKE '".$requestData['search']['value']."%' ";
		$sql.=" OR cidade LIKE '".$requestData['search']['value']."%' ";
		$sql.=" OR uf LIKE '".$requestData['search']['value']."%' ";
		$sql.=" OR status LIKE '".$requestData['search']['value']."%' )";
	}

	$query         = mysqli_query($config, $sql) or die(mysqli_error($config));
	$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. 
	$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
	/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc  */	

	$query         = mysqli_query($config, $sql) or die(mysqli_error($config));
	$data          = array();
	while($row = mysqli_fetch_array($query) ) {  
		// preparing an array

		$nestedData = array(); 

		$nestedData[] = "";
		$nestedData[] = "";
		$data_reversa = date("d/m/Y", strtotime($row["data_criacao"]));
		$nestedData[] = $data_reversa;
		$nestedData[] = $row["razao_social"];
	
		$sql_7 = mysqli_query($config, "SELECT SQL_CACHE nome, sobrenome FROM tb_clientes WHERE CodCli = '".$row["CodCli"]."'") or die(mysqli_error($config));
																									
		if(@mysqli_num_rows($sql_7) <= '0'){
			echo "";
		}else{
			while($r_sql_7 = mysqli_fetch_array($sql_7)){
				$cliente_sel = $r_sql_7[0];
			}
		}	
		
		$nestedData[] = $cliente_sel;
		
		$sql_5 = mysqli_query($config, "SELECT SQL_CACHE categoria FROM tb_categorias WHERE id = '".$row["categoria_base"]."'") or die(mysqli_error($config));
																									
		if(@mysqli_num_rows($sql_5) <= '0'){
			echo "";
		}else{
			while($r_sql_5 = mysqli_fetch_array($sql_5)){
				$categoria = $r_sql_5[0];
			}
		}
		
		$nestedData[] = $categoria;
		$nestedData[] = $row["cidade"];
		$nestedData[] = $row["uf"];
		
		$nestedData[] = "";
		$nestedData[] = "";
		$nestedData[] = "";
		
		switch($row["status"]){
			case 0:
				$status_desc = 'À liberar';
			break;
			case 1:
				$status_desc = 'Liberado';
			break;
			case 2:
				$status_desc = 'Bloqueado';
			break;								
		}			
		
		$nestedData[] = $status_desc;
		$nestedData[] = "<a href=cadastro_edita.php?id_item=".$row["id"].">Editar</a>";;
		$nestedData[] = "<a href='#'>Ação</a>";
		$nestedData[] = "<a href='#'>Ação</a>";
		
		$data[]       = $nestedData;
	}

	$json_data        = array(
		"draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
		"recordsTotal"    => intval( $totalData ),  // total number of records
		"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
		"data"            => $data   // total data array
	);

	echo json_encode($json_data);  // send data as json format

?>

If I search by category, status or user, I can’t do it. I looked and looked through the code, but I couldn’t find a way to improve the search.

  • But within SQL has reference to categoria, status e usuário, did not understand your question, since it is not possible to verify what is happening only with what you posted.

  • At the bottom, there is this record: $nestedData[] = $Row["Uf"]; The script can find it, because it is original, let’s say, it already came in it. I did this select: $sql_5 = mysqli_query($config, "SELECT SQL_CACHE category FROM tb_categories WHERE id = '".$Row["categoria_base"]."'") or die(mysqli_error($config); if(@mysqli_num_rows($sql_5) <= '0'){ echo ""; }Else{ while($r_sql_5 = mysqli_fetch_array($sql_5)){ $categoria = $r_sql_5[0]; } } But the script cannot read this select.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.