Guest User

Untitled

a guest
Dec 12th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.79 KB | None | 0 0
  1. $(document).ready(function() {
  2. var table = $('#example').DataTable( {
  3. "processing": true,
  4. "serverSide": true,
  5. "paging": true,
  6. "pageLength": 10,
  7. "lengthChange": false,
  8. "bInfo": false,
  9. "ordering": false,
  10. "ajax": "server_processing.php",
  11. "columns": [
  12.  
  13. { "data": "codigo_interno" },
  14. { "data": "otros_codigos" },
  15. { "data": "nombre_comun" },
  16. { "data": "compatibilidad" },
  17. { "data": "precio_final" },
  18. { "data": "cantidad" },
  19. {
  20. "targets": -1,
  21. "data": null,
  22. "defaultContent": "<button>Ver</button>"
  23. }
  24. ],
  25.  
  26.  
  27. "language": {
  28. search: "Buscar",
  29. "zeroRecords": "No existen registros"
  30. }
  31. } );
  32.  
  33. $('#example tbody').on( 'click', 'button', function () {
  34. var data = table.row( $(this).parents('tr') ).data();
  35. //alert( data['codigo_interno'] );
  36. var hola = data['codigo_interno'];
  37. location.href="index2.php?id="+hola;
  38.  
  39.  
  40. } );
  41.  
  42.  
  43. } );
  44.  
  45. <?php
  46. $table = 'repuestosfinal';
  47. $primaryKey = 'id_repuestos';
  48.  
  49.  
  50. $columns = array(
  51. array( 'db' => 'codigo_interno', 'dt' => 'codigo_interno' ),
  52. array( 'db' => 'otros_codigos', 'dt' => 'otros_codigos' ),
  53. array( 'db' => 'nombre', 'dt' => 'nombre_comun' ),
  54. array( 'db' => 'compatibilidad', 'dt' => 'compatibilidad' ),
  55. array( 'db' => 'precio_final', 'dt' => 'precio_final' ),
  56. array( 'db' => 'cantidad', 'dt' => 'cantidad' )
  57.  
  58. );
  59.  
  60. $sql_details = array(
  61. 'user' => 'root',
  62. 'pass' => '',
  63. 'db' => 'urizar',
  64. 'host' => 'localhost'
  65. );
  66.  
  67.  
  68. require( 'ssp.class.php' );
  69.  
  70. echo json_encode(
  71. SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
  72. );
  73.  
  74. <?php
  75.  
  76. // REMOVE THIS BLOCK - used for DataTables test environment only!
  77. $file = $_SERVER['DOCUMENT_ROOT'].'/datatables/pdo.php';
  78. if ( is_file( $file ) ) {
  79. include( $file );
  80. }
  81. class SSP {
  82. /**
  83. * Create the data output array for the DataTables rows
  84. *
  85. * @param array $columns Column information array
  86. * @param array $data Data from the SQL get
  87. * @return array Formatted data in a row based format
  88. */
  89. static function data_output ( $columns, $data )
  90. {
  91. $out = array();
  92. for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
  93. $row = array();
  94. for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
  95. $column = $columns[$j];
  96. // Is there a formatter?
  97. if ( isset( $column['formatter'] ) ) {
  98. $row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] );
  99. }
  100. else {
  101. $row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ];
  102. }
  103. }
  104. $out[] = $row;
  105. }
  106. return $out;
  107. }
  108. /**
  109. * Database connection
  110. *
  111. * Obtain an PHP PDO connection from a connection details array
  112. *
  113. * @param array $conn SQL connection details. The array should have
  114. * the following properties
  115. * * host - host name
  116. * * db - database name
  117. * * user - user name
  118. * * pass - user password
  119. * @return resource PDO connection
  120. */
  121. static function db ( $conn )
  122. {
  123. if ( is_array( $conn ) ) {
  124. return self::sql_connect( $conn );
  125. }
  126. return $conn;
  127. }
  128. /**
  129. * Paging
  130. *
  131. * Construct the LIMIT clause for server-side processing SQL query
  132. *
  133. * @param array $request Data sent to server by DataTables
  134. * @param array $columns Column information array
  135. * @return string SQL limit clause
  136. */
  137. static function limit ( $request, $columns )
  138. {
  139. $limit = '';
  140. if ( isset($request['start']) && $request['length'] != -1 ) {
  141. $limit = "LIMIT ".intval($request['start']).", ".intval($request['length']);
  142. }
  143. return $limit;
  144. }
  145. /**
  146. * Ordering
  147. *
  148. * Construct the ORDER BY clause for server-side processing SQL query
  149. *
  150. * @param array $request Data sent to server by DataTables
  151. * @param array $columns Column information array
  152. * @return string SQL order by clause
  153. */
  154. static function order ( $request, $columns )
  155. {
  156. $order = '';
  157. if ( isset($request['order']) && count($request['order']) ) {
  158. $orderBy = array();
  159. $dtColumns = self::pluck( $columns, 'dt' );
  160. for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
  161. // Convert the column index into the column data property
  162. $columnIdx = intval($request['order'][$i]['column']);
  163. $requestColumn = $request['columns'][$columnIdx];
  164. $columnIdx = array_search( $requestColumn['data'], $dtColumns );
  165. $column = $columns[ $columnIdx ];
  166. if ( $requestColumn['orderable'] == 'true' ) {
  167. $dir = $request['order'][$i]['dir'] === 'asc' ?
  168. 'ASC' :
  169. 'DESC';
  170. $orderBy[] = '`'.$column['db'].'` '.$dir;
  171. }
  172. }
  173. if ( count( $orderBy ) ) {
  174. $order = 'ORDER BY '.implode(', ', $orderBy);
  175. }
  176. }
  177. return $order;
  178. }
  179. /**
  180. * Searching / Filtering
  181. *
  182. * Construct the WHERE clause for server-side processing SQL query.
  183. *
  184. * NOTE this does not match the built-in DataTables filtering which does it
  185. * word by word on any field. It's possible to do here performance on large
  186. * databases would be very poor
  187. *
  188. * @param array $request Data sent to server by DataTables
  189. * @param array $columns Column information array
  190. * @param array $bindings Array of values for PDO bindings, used in the
  191. * sql_exec() function
  192. * @return string SQL where clause
  193. */
  194. static function filter ( $request, $columns, &$bindings )
  195. {
  196. $globalSearch = array();
  197. $columnSearch = array();
  198. $dtColumns = self::pluck( $columns, 'dt' );
  199. if ( isset($request['search']) && $request['search']['value'] != '' ) {
  200. $str = $request['search']['value'];
  201. for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
  202. $requestColumn = $request['columns'][$i];
  203. $columnIdx = array_search( $requestColumn['data'], $dtColumns );
  204. $column = $columns[ $columnIdx ];
  205. if ( $requestColumn['searchable'] == 'true' ) {
  206. $binding = self::bind( $bindings, '%'.$str.'%',
  207. PDO::PARAM_STR );
  208. $globalSearch[] = "`".$column['db']."` LIKE ".$binding;
  209. }
  210. }
  211. }
  212. // Individual column filtering
  213. if ( isset( $request['columns'] ) ) {
  214. for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
  215. $requestColumn = $request['columns'][$i];
  216. $columnIdx = array_search( $requestColumn['data'], $dtColumns );
  217. $column = $columns[ $columnIdx ];
  218. $str = $requestColumn['search']['value'];
  219. if ( $requestColumn['searchable'] == 'true' &&
  220. $str != '' ) {
  221. $binding = self::bind( $bindings, '%'.$str.'%',
  222. PDO::PARAM_STR );
  223. $columnSearch[] = "`".$column['db']."` LIKE ".$binding;
  224. }
  225. }
  226. }
  227. // Combine the filters into a single string
  228. $where = '';
  229. if ( count( $globalSearch ) ) {
  230. $where = '('.implode(' OR ', $globalSearch).')';
  231. }
  232. if ( count( $columnSearch ) ) {
  233. $where = $where === '' ?
  234. implode(' AND ', $columnSearch) :
  235. $where .' AND '. implode(' AND ', $columnSearch);
  236. }
  237. if ( $where !== '' ) {
  238. $where = 'WHERE '.$where;
  239. }
  240. return $where;
  241. }
  242. /**
  243. * Perform the SQL queries needed for an server-side processing requested,
  244. * utilising the helper functions of this class, limit(), order() and
  245. * filter() among others. The returned array is ready to be encoded as JSON
  246. * in response to an SSP request, or can be modified if needed before
  247. * sending back to the client.
  248. *
  249. * @param array $request Data sent to server by DataTables
  250. * @param array|PDO $conn PDO connection resource or connection parameters
  251. array
  252. * @param string $table SQL table to query
  253. * @param string $primaryKey Primary key of the table
  254. * @param array $columns Column information array
  255. * @return array Server-side processing response array
  256. */
  257. static function simple ( $request, $conn, $table, $primaryKey, $columns )
  258. {
  259. $bindings = array();
  260. $db = self::db( $conn );
  261. // Build the SQL query string from the request
  262. $limit = self::limit( $request, $columns );
  263. $order = self::order( $request, $columns );
  264. $where = self::filter( $request, $columns, $bindings );
  265. // Main query to actually get the data
  266. $data = self::sql_exec( $db, $bindings,
  267. "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
  268. FROM `$table`
  269. $where
  270. $order
  271. $limit"
  272. );
  273. // Data set length after filtering
  274. $resFilterLength = self::sql_exec( $db, $bindings,
  275. "SELECT COUNT(`{$primaryKey}`)
  276. FROM `$table`
  277. $where"
  278. );
  279. $recordsFiltered = $resFilterLength[0][0];
  280. // Total data set length
  281. $resTotalLength = self::sql_exec( $db,
  282. "SELECT COUNT(`{$primaryKey}`)
  283. FROM `$table`"
  284. );
  285. $recordsTotal = $resTotalLength[0][0];
  286. /*
  287. * Output
  288. */
  289. return array(
  290. "draw" => isset ( $request['draw'] ) ?
  291. intval( $request['draw'] ) :
  292. 0,
  293. "recordsTotal" => intval( $recordsTotal ),
  294. "recordsFiltered" => intval( $recordsFiltered ),
  295. "data" => self::data_output( $columns, $data )
  296. );
  297. }
  298. /**
  299. * The difference between this method and the `simple` one, is that you can
  300. * apply additional `where` conditions to the SQL queries. These can be in
  301. * one of two forms:
  302. *
  303. * * 'Result condition' - This is applied to the result set, but not the
  304. * overall paging information query - i.e. it will not effect the number
  305. * of records that a user sees they can have access to. This should be
  306. * used when you want apply a filtering condition that the user has sent.
  307. * * 'All condition' - This is applied to all queries that are made and
  308. * reduces the number of records that the user can access. This should be
  309. * used in conditions where you don't want the user to ever have access to
  310. * particular records (for example, restricting by a login id).
  311. *
  312. * @param array $request Data sent to server by DataTables
  313. * @param array|PDO $conn PDO connection resource or connection parameters
  314. array
  315. * @param string $table SQL table to query
  316. * @param string $primaryKey Primary key of the table
  317. * @param array $columns Column information array
  318. * @param string $whereResult WHERE condition to apply to the result set
  319. * @param string $whereAll WHERE condition to apply to all queries
  320. * @return array Server-side processing response array
  321. */
  322. static function complex ( $request, $conn, $table, $primaryKey, $columns,
  323. $whereResult=null, $whereAll=null )
  324. {
  325. $bindings = array();
  326. $db = self::db( $conn );
  327. $localWhereResult = array();
  328. $localWhereAll = array();
  329. $whereAllSql = '';
  330. // Build the SQL query string from the request
  331. $limit = self::limit( $request, $columns );
  332. $order = self::order( $request, $columns );
  333. $where = self::filter( $request, $columns, $bindings );
  334. $whereResult = self::_flatten( $whereResult );
  335. $whereAll = self::_flatten( $whereAll );
  336. if ( $whereResult ) {
  337. $where = $where ?
  338. $where .' AND '.$whereResult :
  339. 'WHERE '.$whereResult;
  340. }
  341. if ( $whereAll ) {
  342. $where = $where ?
  343. $where .' AND '.$whereAll :
  344. 'WHERE '.$whereAll;
  345. $whereAllSql = 'WHERE '.$whereAll;
  346. }
  347. // Main query to actually get the data
  348. $data = self::sql_exec( $db, $bindings,
  349. "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
  350. FROM `$table`
  351. $where
  352. $order
  353. $limit"
  354. );
  355. // Data set length after filtering
  356. $resFilterLength = self::sql_exec( $db, $bindings,
  357. "SELECT COUNT(`{$primaryKey}`)
  358. FROM `$table`
  359. $where"
  360. );
  361. $recordsFiltered = $resFilterLength[0][0];
  362. // Total data set length
  363. $resTotalLength = self::sql_exec( $db, $bindings,
  364. "SELECT COUNT(`{$primaryKey}`)
  365. FROM `$table` ".
  366. $whereAllSql
  367. );
  368. $recordsTotal = $resTotalLength[0][0];
  369. /*
  370. * Output
  371. */
  372. return array(
  373. "draw" => isset ( $request['draw'] ) ?
  374. intval( $request['draw'] ) :
  375. 0,
  376. "recordsTotal" => intval( $recordsTotal ),
  377. "recordsFiltered" => intval( $recordsFiltered ),
  378. "data" => self::data_output( $columns, $data )
  379. );
  380. }
  381. /**
  382. * Connect to the database
  383. *
  384. * @param array $sql_details SQL server connection details array, with the
  385. * properties:
  386. * * host - host name
  387. * * db - database name
  388. * * user - user name
  389. * * pass - user password
  390. * @return resource Database connection handle
  391. */
  392. static function sql_connect ( $sql_details )
  393. {
  394. try {
  395. $db = @new PDO(
  396. "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
  397. $sql_details['user'],
  398. $sql_details['pass'],
  399. array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
  400. );
  401. }
  402. catch (PDOException $e) {
  403. self::fatal(
  404. "An error occurred while connecting to the database. ".
  405. "The error reported by the server was: ".$e->getMessage()
  406. );
  407. }
  408. return $db;
  409. }
  410. /**
  411. * Execute an SQL query on the database
  412. *
  413. * @param resource $db Database handler
  414. * @param array $bindings Array of PDO binding values from bind() to be
  415. * used for safely escaping strings. Note that this can be given as the
  416. * SQL query string if no bindings are required.
  417. * @param string $sql SQL query to execute.
  418. * @return array Result from the query (all rows)
  419. */
  420. static function sql_exec ( $db, $bindings, $sql=null )
  421. {
  422. // Argument shifting
  423. if ( $sql === null ) {
  424. $sql = $bindings;
  425. }
  426. $stmt = $db->prepare( $sql );
  427. //echo $sql;
  428. // Bind parameters
  429. if ( is_array( $bindings ) ) {
  430. for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
  431. $binding = $bindings[$i];
  432. $stmt->bindValue( $binding['key'], $binding['val'],
  433. $binding['type'] );
  434. }
  435. }
  436. // Execute
  437. try {
  438. $stmt->execute();
  439. }
  440. catch (PDOException $e) {
  441. self::fatal( "An SQL error occurred: ".$e->getMessage() );
  442. }
  443. // Return all
  444. return $stmt->fetchAll( PDO::FETCH_BOTH );
  445. }
  446. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  447. * Internal methods
  448. */
  449. /**
  450. * Throw a fatal error.
  451. *
  452. * This writes out an error message in a JSON string which DataTables will
  453. * see and show to the user in the browser.
  454. *
  455. * @param string $msg Message to send to the client
  456. */
  457. static function fatal ( $msg )
  458. {
  459. echo json_encode( array(
  460. "error" => $msg
  461. ) );
  462. exit(0);
  463. }
  464. /**
  465. * Create a PDO binding key which can be used for escaping variables safely
  466. * when executing a query with sql_exec()
  467. *
  468. * @param array &$a Array of bindings
  469. * @param * $val Value to bind
  470. * @param int $type PDO field type
  471. * @return string Bound key to be used in the SQL where this parameter
  472. * would be used.
  473. */
  474. static function bind ( &$a, $val, $type )
  475. {
  476. $key = ':binding_'.count( $a );
  477. $a[] = array(
  478. 'key' => $key,
  479. 'val' => $val,
  480. 'type' => $type
  481. );
  482. return $key;
  483. }
  484. /**
  485. * Pull a particular property from each assoc. array in a numeric array,
  486. * returning and array of the property values from each item.
  487. *
  488. * @param array $a Array to get data from
  489. * @param string $prop Property to read
  490. * @return array Array of property values
  491. */
  492. static function pluck ( $a, $prop )
  493. {
  494. $out = array();
  495. for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
  496. $out[] = $a[$i][$prop];
  497. }
  498. return $out;
  499. }
  500. /**
  501. * Return a string from an array or a string
  502. *
  503. * @param array|string $a Array to join
  504. * @param string $join Glue for the concatenation
  505. * @return string Joined string
  506. */
  507. static function _flatten ( $a, $join = ' AND ' )
  508. {
  509. if ( ! $a ) {
  510. return '';
  511. }
  512. else if ( $a && is_array($a) ) {
  513. return implode( $join, $a );
  514. }
  515. return $a;
  516. }
  517. }
Add Comment
Please, Sign In to add comment