PHP Classes

File: tables.php

Recommend this page to a friend!
  Classes of Mehmet Kidiman  >  Developbat PHP CRUD  >  tables.php  >  Download  
File: tables.php
Role: Auxiliary script
Content type: text/plain
Description: Auxiliary script
Class: Developbat PHP CRUD
Show pages to manage table records using Bootstrap
Author: By
Last change:
Date: 11 months ago
Size: 14,285 bytes
 

Contents

Class file image Download
<?php

include('header.php');

//$tableId = randomString();
$output = '';

//var_dump($_SESSION);

if (isset($_POST['table_name_order']) && $_POST['action'] == 'update') {

    $arrayKeys = array_keys($_POST);
    $tableNamePost = $_POST['table_name_order'];
    $output = updateData($connect, $_POST);
    $selectedTable = $tableNamePost;
}

if (isset($_POST['table_name_order']) && $_POST['action'] == 'add') {

    $arrayKeys = array_keys($_POST);
    $tableNamePost = $_POST['table_name_order'];
    $output = insertData($connect, $_POST);
    $selectedTable = $tableNamePost;
}

//var_dump($selectedTable);
$columns = showColums($connect, $selectedTable);
$tableDraw = '';
echo '<div class="row">';
echo '<div class="col-md-12">';


echo '<div class="row">
                    	<div class="col-lg-12 col-md-12 col-sm-2 col-xs-12">';

$tables = showTables($connect, $showTables);

foreach ($tables as $table) {

    echo '<div style="float:left; margin-right:2px;">';
    echo '<form  id="t_' . $table[0] . '"  action="tables.php" method="post">';


    echo '<input  type="hidden" name="table_name" value="' . $table[0] . '" ></input>';
    if ($selectedTable == $table[0]) {
        echo '<input type="submit" value="' . $table[0] . '"  class="btn btn-primary " />';
    } else {
        echo '<input type="submit" value="' . $table[0]. '"  class="btn btn-default " />';
    }

    echo '</form>';
    echo '</div>';
}
    echo '</div></div>';

echo '<div class="panel panel-default">
                <div class="panel-heading">
                	<div class="row">
                    	<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">';

echo '<div id="infoDiv"></div>';
if ($output != '') {
    echo '<div class="alert alert-info" id="alertDiv" role="alert">' . $output . '</div>';
}
echo '
                            <button  class="btn btn-success btn-md addBtn"> Add</button>  
                             <button  class="btn btn-danger btn-md toPdf"> Table To Pdf </button> 
                             <button  class="btn btn-primary btn-md toExcel"> Result To Excel <span id="resulCount" class="badge badge-light"></span></button> 
                             <span class="badge badge-success" id="actionDivSearch"></span>
                            </div>  	
                        </div>
                    </div>
                </div>';

/*
echo '<div class="table-responsive">';
echo '<table class="table-bordered" ><tr>';
foreach ($columns as $column) {
    $typePart = explode("(", $column[1]);
    $inputType = inputType($typePart[0]);
    echo '<td><div class="inner-addon left-addon">
    <i class="glyphicon glyphicon-search"></i>
    <input type="'.$inputType.'" class="form-control" id="' . $column [0] . '" placeholder="' . $column [0] . '" />
</div>
</td>';
}
echo '</tr></table>';*/

echo '<table id="generaltable" class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
foreach ($columns as $column) {
if($column [3] == 'PRI'){
    $priClass = 'bg-light';
}else{
    $priClass = 'bg-default';
}
    //<span class="badge badge-warning">' . $column [3] . '</span> // PRI
    echo '<th class="'.$priClass.'" title="' . $column [1] . '">       
           <strong/>' . $column [0] . '</strong>
           </th>';

}
echo '<th></th><th></th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';

echo '</tbody>';
echo '</table>';
echo '</div>';


echo '</div>';
echo '</div>';

?>
    <!-- Modal -->
    <div class="modal fade" id="actionModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">Data Modal</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="actionDiv"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        var dataTables;
        var cloumnArray = <?php echo json_encode($columns); ?>;
        var tableName = '<?php echo $selectedTable; ?>';
        var tableResults = [];
        var tableExcel = [];
        var searchInputsIds ='';




        $(document).ready(function () {

          /*  $('.searchinputs .input').keyup(function (event) {
                console.log(event);
            });*/


            $('#generaltable thead tr').clone(true).appendTo( '#generaltable thead' );

            $('#generaltable thead tr:eq(1) th').each( function (i) {

                var title = $(this).text().replace(/\s/g, "");
                if(title != ''){
                $(this).html( '<div class="inner-addon right-addon"><i id="g_'+title+'" class="glyphicon glyphicon-search"></i><input id="i_'+title+'" class="form-control searchinputs" type="text" placeholder="'+title+'" /></div>' );

                $( 'input', this ).on( 'keyup change', function () {
                    if ( dataTables.column(i).search() !== this.value ) {
                        dataTables
                            .column(i)
                            .search( this.value )
                            .draw();
                    }
                } );
                }
            } );


            dataTables = $('#generaltable').DataTable({
                "dom": 'lrtip',
                "searching" :true,
                "processing": true,
                oLanguage: {
                    sLoadingRecords: '<img width="100" height="100" src="img/loading.gif"/>'
                },
                fixedHeader: {
                    header: true,
                    footer: true,
                    headerOffset: 50
                },
                orderCellsTop: true,
                "order":[],
                "ajax": {
                    url: "table_fetch.php",
                    type: "POST",
                    "data": {
                        "table": tableName
                    },
                },
                columnDefs: [{targets: [0], orderData: [0, 1]}, {targets: [1], orderData: [1, 0]}, {
                    targets: [4],
                    orderData: [4, 0]
                }],

            });


            dataTables.on('search.dt', function() {
                $('#actionDivSearch').html('Seach result : ' + dataTables.rows( { filter : 'applied'} ).nodes().length + ' record..');
                $('#resulCount').html(dataTables.rows( { filter : 'applied'} ).nodes().length);
                tableResults =  dataTables.rows( { filter : 'applied'} ).data();
            });

            $('.toExcel').click(function () {

                for(tb=0; tb < tableResults.length; tb++){
                    rowNames = [];
                    row =tableResults[tb].slice(0,-2)

                    for (r =0; r < row.length; r++){
                        rowNames[cloumnArray[r][0]] =  row[r];
                    }
                    //console.log(rowNames);
                    tableExcel.push(rowNames); ////***
                }
                //console.log(tableExcel);
                filename = tableName+'-results.xlsx';
                var ws = XLSX.utils.json_to_sheet(tableExcel);
                var wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, "table");
                XLSX.writeFile(wb,filename);
            });

            $('.addBtn').click(function () {
                var btnaction = 'add';
                var tableName = '<?php echo $selectedTable; ?>';
                $.ajax({
                    url: "data_action.php",
                    method: "POST",
                    data: {tableName: tableName, action: btnaction},
                    // dataType:"json",
                    beforeSend: function () {
                        $('.modal-title').html(" <i class='glyphicon glyphicon-pencil'></i> Add Data For "+ tableName);
                        $('#actionModal').modal('show');

                    },
                    success: function (data) {
                        $('#actionDiv').html(data);

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $('#alertDiv').html("ERROR:" + xhr.responseText + " - " + thrownError);
                    },
                    complete: function () {
                        //$("#" + idString).css("color", "red");

                    }
                })
            });


            $(document).on('submit', '#updateForm', function (event) {
                console.log('---------update---------------');
                event.preventDefault();
                $('#action').attr('disabled', 'disabled');
                var form_data = $(this).serialize();
                $.ajax({
                    url: "update_action.php",
                    method: "POST",
                    data: form_data,
                    success: function (data) {
                        $('#updateForm')[0].reset();
                        $('#actionModal').modal('hide');
                        $('#infoDiv').fadeIn().html('<div class="alert alert-success">' + data + '</div>');
                        $('#action').attr('disabled', false);
                        dataTables.ajax.reload();
                    }
                })
            });


            $('.toPdf').click(function () {

                var doc = new jsPDF('p', 'pt');
                var elem = document.getElementById("generaltable");
                var res = doc.autoTableHtmlToJson(elem);
                doc.autoTable(res.columns, res.data);
                doc.save("table.pdf");
            });

        });

        function showFiles(id){
            $('.modal-title').html("<i class='glyphicon glyphicon-file'></i> ?mages ");
            $('#actionModal').modal('show');

            var htmlim = '';
            var files = $('#'+id).val();
            //console.log(files);
            var fileArr = files.split('-');
            for (i=0; i < fileArr.length; i++){
                if(fileArr[i] != ''){
                    htmlim += '<a target="_blank" href="'+fileArr[i]+'"><img class="img-thumbnail" src="' + fileArr[i] + '" /></a>';
                }
            }
            $('#actionDiv').html(htmlim);
        }

        function dellTable(id) {
            var tableName = '<?php echo $_SESSION['selectedtable']; ?>';
            var idString = id;
            var btnaction = 'dell';

            var alertConfirm = confirm("Do you want to remove ? The record is : ID : " + idString + " Table : " + tableName);

            if (alertConfirm == true) {

                $.ajax({
                    url: "data_action.php",
                    method: "POST",
                    data: {tableName: tableName, dataId: idString, action: btnaction},
                    // dataType:"json",
                    beforeSend: function () {
                        //

                    },
                    success: function (data) {
                        $('#actionDiv').html(data);
                        dataTables.ajax.reload();

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        // alert("ERROR:" + xhr.responseText+" - "+thrownError);
                        $('#actionDiv').html("ERROR:" + xhr.responseText + " - " + thrownError);
                    },
                    complete: function () {
                        $("#" + idString).css("color", "red");
                    }
                })
            } else {
                $('#actionDiv').html('Delete Cancelled..');
            }
        }
    </script>
    <script>
        var uploadedImages = [];
        var imagesShow = '';
        $(document).ready(function(){
            $(document).on('change', '#files', function(){
                var name = document.getElementById("files").files[0].name;
                var form_data = new FormData();
                var ext = name.split('.').pop().toLowerCase();
                if(jQuery.inArray(ext, ['gif','png','jpg','jpeg','doc','docx',,'pdf']) == -1)
                {
                    alert("Invalid Image File");
                }
                var oFReader = new FileReader();
                oFReader.readAsDataURL(document.getElementById("files").files[0]);
                var f = document.getElementById("files").files[0];
                var fsize = f.size||f.fileSize;
                if(fsize > 2000000)
                {
                    alert("Image File Size is very big");
                }
                else
                {
                    form_data.append("file", document.getElementById('files').files[0]);
                    $.ajax({
                        url:"upload.php",
                        method:"POST",
                        data: form_data,
                        contentType: false,
                        cache: false,
                        processData: false,
                        beforeSend:function(){
                            $('#resultimages').html("<label class='text-success'>Image Uploading...</label>");
                        },
                        success:function(data)
                        {
                            imagesShow='';
                            uploadedImages.push(data);
                            $('#filesinput').val(JSON.stringify(uploadedImages));
                            for(im=0; im < uploadedImages.length; im++){
                                imagesShow +='<img style="float:left" class="img-thumbnail"  width="75px" height="100px" src="' + uploadedImages[im] + '" />'
                            }
                            $('#resultimages').html(imagesShow);
                        }
                    });
                }
            });
        });

    </script>
<?php
include('footer.php');
?>
For more information send a message to info at phpclasses dot org.