PHPIndex

This page lists files in the current directory. You can view content, get download/execute commands for Wget, Curl, or PowerShell, or filter the list using wildcards (e.g., `*.sh`).

columns.php
wget 'https://lists2.roe3.org/cruddiy/columns.php'
View Content
<!doctype html>
<html lang="en">
<head>
    <title>Select Columns</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

</head>
<body class="bg-light">
<section class="py-5">
    <div class="container bg-white shadow py-5">
        <div class="row">
            <div class="col-md-12 mx-auto">
                <div class="text-center">
                    <h4 class="h1 border-bottom pb-2">All Available Columns</h4>
                </div>

                <div class="col-md-10 mx-atuo text-right pr-5 ml-4">
                    <input type="checkbox" id="checkall">
                    <label for="checkall">Check/uncheck all</label>
                </div>


                <form class="form-horizontal" action="generate.php" method="post">
                    <fieldset>
                        <?php

                        include "app/config.php";

                        function get_primary_keys($table){
                            global $link;
                            $sql = "SHOW KEYS FROM $table WHERE Key_name = 'PRIMARY'";
                            $result = mysqli_query($link,$sql);
							$primary_keys = Array();
                            while($row = mysqli_fetch_assoc($result))
                            {
                                $primary_keys[] = $row['Column_name'];
                            }
                            return $primary_keys;
                        }

                        function get_autoincrement_cols($table){
                            global $link;
                            $sql = "DESCRIBE $table";
                            $result = mysqli_query($link,$sql);
							$auto_keys = Array();
                            while($row = mysqli_fetch_assoc($result))
                            {
                                if ($row['Extra'] == 'auto_increment') {
                                    $auto_keys[] = $row['Field'];
                                }
                            }
                            return $auto_keys;
                        }

                        function get_col_types($table,$column){
                            global $link; 
                            $sql = "SHOW FIELDS FROM $table where FIELD ="."'".$column."'";
                            $result = mysqli_query($link,$sql);
                            $row = mysqli_fetch_assoc($result);
                            return $row['Type'] ;
                            mysqli_free_result($result);
                        }

                        function get_foreign_keys($table){
                            global $link;
                            global $db_name;
                            $fks[] = "";
                            $sql = "SELECT k.COLUMN_NAME as 'Foreign Key'
                                    FROM information_schema.TABLE_CONSTRAINTS i
                                    LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME
                                    WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' AND i.TABLE_NAME = '$table'";
                            $result = mysqli_query($link,$sql);
                            while($row = mysqli_fetch_assoc($result))
                            {
                                $fks[] = $row['Foreign Key'];
                            }
                            return $fks;
                            mysqli_free_result($result);
                        }

                        $checked_tables_counter=0;
                        if ( isset( $_POST['table'] ) )
                        {
                            foreach ( $_POST['table'] as $table )
                            {
                                $i=0;
                                if (isset($table['tablecheckbox']) && $table['tablecheckbox'] == 1) {
                                    $tablename = $table['tablename'];
                                    $tabledisplay = $table['tabledisplay'];
                                    echo "<div class='text-center mb-4'><b>Table: " . $tabledisplay . " (". $tablename .")</b></div>";
                                    $sql = "SHOW columns FROM $tablename";
                                    $primary_keys = get_primary_keys($tablename);
                                    $auto_keys = get_autoincrement_cols($tablename);
                                    $foreign_keys = get_foreign_keys($tablename);

                                    $result = mysqli_query($link,$sql);
                                    while ($column = mysqli_fetch_array($result)) {

                                        $column_type = get_col_types($tablename,$column[0]);

                                        if (in_array ("$column[0]", $primary_keys)) {
                                            $primary = "🔑";
                                            echo '<input type="hidden" name="'.$tablename.'columns['.$i.'][primary]" value="'.$primary.'"/>';
                                        }
                                        else {
                                            $primary = "";
                                        }

                                        if (in_array ("$column[0]", $auto_keys)) {
                                            $auto = "🔒";
                                            echo '<input type="hidden" name="'.$tablename.'columns['.$i.'][auto]" value="'.$auto.'"/>';
                                        }
                                        else {
                                            $auto = "";
                                        }

                                        if (in_array ("$column[0]", $foreign_keys)) {
                                            $fk = "🛅";
                                            echo '<input type="hidden" name="'.$tablename.'columns['.$i.'][fk]" value="'.$fk.'"/>';
                                        }
                                        else {
                                            $fk = "";
                                        }

                                        echo '<div class="row align-items-center mb-2">
                                    <div class="col-2 text-right"
                                        <label class="col-form-label" for="'.$tablename.'">'. $primary . $auto . $fk . $column[0] . ' </label>
                                    </div>
                                    <div class="col-md-6">
                                        <input type="hidden" name="'.$tablename.'columns['.$i.'][tablename]" value="'.$tablename.'"/>
                                        <input type="hidden" name="'.$tablename.'columns['.$i.'][tabledisplay]" value="'.$tabledisplay.'"/>
                                        <input type="hidden" name="'.$tablename.'columns['.$i.'][columnname]" value="'.$column[0].'"/>
                                        <input type="hidden" name="'.$tablename.'columns['.$i.'][columntype]" value="'.$column_type.'"/>
                                        <input id="textinput_'.$tablename. '-'.$i.'"name="'. $tablename. 'columns['.$i.'][columndisplay]" type="text" placeholder="Display field name in frontend" class="form-control rounded-0">
                                    </div>
                                    <div class="col-md-4">
                                        <input type="checkbox"  name="'.$tablename.'columns['.$i.'][columnvisible]" id="checkboxes-'.$checked_tables_counter.'-'.$i.'" value="1">
                                <label for="checkboxes-'.$checked_tables_counter.'-'.$i.'">Visible in overview?</label></div>
                     </div>';
                                        $i++;
                                    }
                                    $checked_tables_counter++;
                                }
                            }
                        }
                        ?>

                        <div class="row">
                            <div class="col-md-8 mx-auto">
                                <p class="form-check">
                                    <small id="passwordHelpBlock" class="form-text text-muted">
                                        Cruddiy will create a fresh startpage in the app/ sub-folder, with link<?php echo $checked_tables_counter > 1 ? 's' : '' ?> to manage the table<?php echo $checked_tables_counter > 1 ? 's' : '' ?> above.<br>
                                        If you have used Cruddiy on other tables before, your start page will be replaced by the fresh one, and previous links will be lost.
                                    </small>
                                    <input class="form-check-input" type="checkbox" value="true" id="keep_startpage" name="keep_startpage">
                                    <label class="form-check-label" for="keep_startpage">
                                        Keep previously generated startpage and CRUD pages if they exist
                                    </label>
                                    <br>
                                    <input class="form-check-input" type="checkbox" value="true" id="append_links" name="append_links">
                                    <label class="form-check-label" for="append_links">
                                        Append new link<?php echo $checked_tables_counter > 1 ? 's' : '' ?> to previously generated startpage if necessary
                                    </label>
                                </p>
                            </div>
                            <div class="col-md-8 mx-auto">
                                <button type="submit" id="singlebutton" name="singlebutton" class="btn btn-success btn-block rounded-0 shadow-sm">Generate Pages</button>
                            </div>
                        </div>
                    </fieldset>
                </form>
            </div>
        </div>
    </div>
</section>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
    $('#checkall').click(function(e) {
        var chb = $('.form-horizontal').find('input[type="checkbox"]');
        chb.prop('checked', !chb.prop('checked'));
    });
});
</script>
</body>
</html>
generate.php
wget 'https://lists2.roe3.org/cruddiy/generate.php'
View Content
<?php

$total_postvars = count($_POST, COUNT_RECURSIVE);
$max_postvars = ini_get("max_input_vars"); 
if ($total_postvars >= $max_postvars) {
    echo "Uh oh, it looks like you're trying to use more variables than your PHP settings (<a href='https://www.php.net/manual/en/info.configuration.php#ini.max-input-vars'>max_input_variables</a>) allow! <br>";
    echo "Go back and choose fewer tables and/or columns or change your php.ini setting. <br>";      
    echo "Read <a href='https://betterstudio.com/blog/increase-max-input-vars-limit/'>here</a> how you can increase this limit.<br>";
    echo "Cruddiy will now exit because only part of what you wanted would otherwise be generated. 🙇";
    exit();
}

require "app/config.php";
require "templates.php";
$tablename = '';
$tabledisplay = '';
$columnname = '' ;
$columndisplay = '';
$columnvisible = '';
$index_table_rows = '';
$index_table_headers = '';
$sort = '';
$excluded_keys = array('singlebutton', 'keep_startpage', 'append_links');
$generate_start_checked_links = array();
$startpage_filename = "app/navbar.php";
$forced_deletion = false;
$buttons_delimiter = '<!-- TABLE_BUTTONS -->';

function column_type($columnname){
    switch ($columnname) {
        case (preg_match("/text/i", $columnname) ? true : false) :
            return 1;
        break;
        case (preg_match("/enum/i", $columnname) ? true : false) :
            return 2;
        break;
        case (preg_match("/varchar/i", $columnname) ? true : false) :
            return 3;
        break;
            //Tinyint needs work to be selectable from dropdown list
            //So for now a tinyint will be just a input field (in Create)
            //and a prefilled input field (in Update).
        case (preg_match("/tinyint\(1\)/i", $columnname) ? true : false) :
            return 5;
        break;
        case (preg_match("/int/i", $columnname) ? true : false) :
            return 5;
        break;
        case (preg_match("/decimal/i", $columnname) ? true : false) :
            return 6;
        break;
        case (preg_match("/datetime/i", $columnname) ? true : false) :
            return 8;
        break;
        case (preg_match("/date/i", $columnname) ? true : false) :
            return 7;
        break;
        default:
            return 0;
        break;
    }
}

function generate_error(){
    global $errorfile;
    if (!file_put_contents("app/error.php", $errorfile, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating Error file<br>";
}

function generate_startpage(){
    global $startfile; 
    global $appname;
    $step0 = str_replace("{APP_NAME}", $appname, $startfile );
    if (!file_put_contents("app/index.php", $step0, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating main index file.<br>";

}

function generate_userauth(){
    global $userauth; 
    global $appname;
    $step0 = str_replace("{APP_NAME}", $appname, $userauth );
    if (!file_put_contents("app/userauth.php", $step0, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating userauth.php script.<br>";
}

function generate_stylesheet(){
    global $stylesheet; 
    if (!file_put_contents("app/style.css", $stylesheet, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating stylesheet.<br>";
}

function generate_export2excel($tablename){
    global $export2excel;
    $step0 = str_replace("{TABLE_NAME}", $tablename, $export2excel);
if (!file_put_contents("app/export.php", $step0, LOCK_EX)) {
        die("Unable to open file!");
    }

    echo "Generating Excel Export Script.<br>";
}

function generate_login($tablename){
    global $login; 
    global $appname;
    $step0 = str_replace("{TABLE_NAME}", $tablename, $login);
    $step1 = str_replace("{APP_NAME}",$appname,$step0);
    if (!file_put_contents("app/login.php", $step1, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating login script.<br>";
}

function generate_logout(){
    global $logout; 
    if (!file_put_contents("app/logout.php", $logout, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating logout script.<br>";
}

function generate_signup($tablename){
    global $signup;
    global $appname;
    $step0 = str_replace("{TABLE_NAME}", $tablename,$signup);
    $step1 = str_replace("{APP_NAME}",$appname,$step0);
    if (!file_put_contents("app/sign-up.php", $step1, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating sign-up script.<br>";
}

function generate_navbar($tablename, $start_page, $keep_startpage, $append_links, $td){
    global $navbarfile;
    global $generate_start_checked_links;
    global $startpage_filename;

    echo "<h3>Table: $tablename</h3>";

    // make sure that a previous startpage was created before trying to keep it alive
    if (!$keep_startpage || ($keep_startpage && !file_exists($startpage_filename))) {
        if (!file_exists($startpage_filename)) {
            // called on the first run of the POST loop
            echo "Generating fresh Startpage file<br>";
            $step0 = str_replace("{TABLE_BUTTONS}", $start_page, $navbarfile);
            if (!file_put_contents($startpage_filename, $step0, LOCK_EX)) {
                die("Unable to open fresh startpage file!");
            }
        } else {
            // called on subsequent runs of the POST loop
            echo "Populating Startpage file<br>";
            $navbarfile = file_get_contents($startpage_filename);
            if (!$navbarfile) {
                die("Unable to open existing startpage file!");
            }
            append_links_to_navbar($navbarfile, $start_page, $startpage_filename, $generate_start_checked_links,$td);
        }
    } else {
        if ($append_links) {
            // load existing template
            echo "Retrieving existing Startpage file<br>";
            $navbarfile = file_get_contents($startpage_filename);
            if (!$navbarfile) {
                die("Unable to open existing startpage file!");
            }
            append_links_to_navbar($navbarfile, $start_page, $startpage_filename, $generate_start_checked_links,$td);
        }
    }
}

function append_links_to_navbar($navbarfile, $start_page, $startpage_filename, $generate_start_checked_links, $td) {
    global $buttons_delimiter;
    global $appname;

    // extract existing links from app/index.php
    echo "Looking for new link to append to Startpage file<br>";
    $navbarfile_appended = $navbarfile;
    $link_matcher_pattern = '/href=["\']?([^"\'>]+)["\']?/im';
    preg_match_all($link_matcher_pattern, $navbarfile, $navbarfile_links);
    if (count($navbarfile_links)) {
        foreach($navbarfile_links[1] as $navbarfile_link) {
            // echo '- Found existing link '.$navbarfile_link.'<br>';
        }
    }

    // do not append links to app/index.php if they already exist
    preg_match_all($link_matcher_pattern, $start_page, $start_page_links);
    if (count($start_page_links)) {
        foreach($start_page_links[1] as $start_page_link) {
            if (!in_array($start_page_link, $generate_start_checked_links)) {
                if (in_array($start_page_link, $navbarfile_links[1])) {
                    echo '- Not appending '.$start_page_link.' as it already exists<br>';
                } else {
                    echo '- Appending '.$start_page_link.'<br>';
                    array_push($navbarfile_links[1], $start_page_link);
                    $button_string = "\t".'<a class="dropdown-item" href="'.$start_page_link.'">'.$td.'</a>'."\n\t".$buttons_delimiter;
                    $step0 = str_replace($buttons_delimiter, $button_string, $navbarfile);
                    $step1 = str_replace("{APP_NAME}", $appname, $step0 );
                    if (!file_put_contents($startpage_filename, $step1, LOCK_EX)) {
                        die("Unable to open file!");
                    }
                }
                array_push($generate_start_checked_links, $start_page_link);
            }
        }
    }
}


function generate_index($tablename,$tabledisplay,$index_table_headers,$index_table_rows,$column_id, $columns_available, $index_sql_search) {
    global $indexfile;
    global $appname;

    $columns_available = implode("', '", $columns_available);
    $step0 = str_replace("{TABLE_NAME}", $tablename, $indexfile);
    $step1 = str_replace("{TABLE_DISPLAY}", $tabledisplay, $step0);
    $step2 = str_replace("{INDEX_QUERY}", "SELECT * FROM $tablename", $step1 );
    $step3 = str_replace("{INDEX_TABLE_HEADERS}", $index_table_headers, $step2 );
    $step4 = str_replace("{INDEX_TABLE_ROWS}", $index_table_rows, $step3 );
    $step5 = str_replace("{COLUMN_ID}", $column_id, $step4 );
    $step6 = str_replace("{COLUMN_NAME}", $column_id, $step5 );
    $step7 = str_replace("{COLUMNS}", $columns_available, $step6 );
    $step8 = str_replace("{INDEX_CONCAT_SEARCH_FIELDS}", $index_sql_search, $step7 );
    $step9 = str_replace("{APP_NAME}", $appname, $step8 );
    if (!file_put_contents("app/".$tablename."-index.php", $step9, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating $tablename Data Management Index file<br>";
}

function generate_index2($tablename,$tabledisplay,$index_table_headers,$index_table_rows,$column_id, $columns_available, $index_sql_search) {
    global $index2file;
    global $appname;

    $columns_available = implode("', '", $columns_available);
    $step0 = str_replace("{TABLE_NAME}", $tablename, $index2file);
    $step1 = str_replace("{TABLE_DISPLAY}", $tabledisplay, $step0);
    $step2 = str_replace("{INDEX_QUERY}", "SELECT * FROM $tablename", $step1 );
    $step3 = str_replace("{INDEX_TABLE_HEADERS}", $index_table_headers, $step2 );
    $step4 = str_replace("{INDEX_TABLE_ROWS}", $index_table_rows, $step3 );
    $step5 = str_replace("{COLUMN_ID}", $column_id, $step4 );
    $step6 = str_replace("{COLUMN_NAME}", $column_id, $step5 );
    $step7 = str_replace("{COLUMNS}", $columns_available, $step6 );
    $step8 = str_replace("{INDEX_CONCAT_SEARCH_FIELDS}", $index_sql_search, $step7 );
    $step9 = str_replace("{APP_NAME}", $appname, $step8 );
    if (!file_put_contents("app/".$tablename."-index2.php", $step9, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating $tablename View-Only Index file<br>";
}

function generate_read($tablename, $column_id, $read_records){
    global $readfile;
    $step0 = str_replace("{TABLE_NAME}", $tablename, $readfile);
    $step1 = str_replace("{TABLE_ID}", $column_id, $step0);
    $step2 = str_replace("{RECORDS_READ_FORM}", $read_records, $step1 );
    if (!file_put_contents("app/".$tablename."-read.php", $step2, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating $tablename Read file<br>";
}

function generate_delete($tablename, $column_id){
    global $deletefile;
    $step0 = str_replace("{TABLE_NAME}", $tablename, $deletefile);
    $step1 = str_replace("{TABLE_ID}", $column_id, $step0);
    if (!file_put_contents("app/".$tablename."-delete.php", $step1, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating $tablename Delete file<br><br>";
}

function generate_create($tablename,$create_records, $create_err_records, $create_sqlcolumns, $create_numberofparams, $create_sql_params, $create_html, $create_postvars) {
    global $createfile;
    $step0 = str_replace("{TABLE_NAME}", $tablename, $createfile);
    $step1 = str_replace("{CREATE_RECORDS}", $create_records, $step0);
    $step2 = str_replace("{CREATE_ERR_RECORDS}", $create_err_records, $step1);
    $step3 = str_replace("{CREATE_COLUMN_NAMES}", $create_sqlcolumns, $step2);
    $step4 = str_replace("{CREATE_QUESTIONMARK_PARAMS}", $create_numberofparams, $step3);
    $step5 = str_replace("{CREATE_SQL_PARAMS}", $create_sql_params, $step4 );
    $step6 = str_replace("{CREATE_HTML}", $create_html, $step5);
    $step7 = str_replace("{CREATE_POST_VARIABLES}", $create_postvars, $step6);
    if (!file_put_contents("app/".$tablename."-create.php", $step7, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating $tablename Create file<br>";
}

function generate_update($tablename, $create_records, $create_err_records, $create_postvars, $column_id, $create_html, $update_sql_params, $update_sql_id, $update_column_rows, $update_sql_columns){
    global $updatefile;
    $step0 = str_replace("{TABLE_NAME}", $tablename, $updatefile);
    $step1 = str_replace("{CREATE_RECORDS}", $create_records, $step0);
    $step2 = str_replace("{CREATE_ERR_RECORDS}", $create_err_records, $step1);
    $step3 = str_replace("{COLUMN_ID}", $column_id, $step2);
    $step4 = str_replace("{UPDATE_SQL_PARAMS}", $update_sql_params, $step3);
    $step5 = str_replace("{UPDATE_SQL_ID}", $update_sql_id, $step4 );
    $step6 = str_replace("{CREATE_HTML}", $create_html, $step5);
    $step7 = str_replace("{CREATE_POST_VARIABLES}", $create_postvars, $step6);
    $step8 = str_replace("{UPDATE_COLUMN_ROWS}", $update_column_rows, $step7);
    $step9 = str_replace("{UPDATE_SQL_COLUMNS}", $update_sql_columns, $step8);
    if (!file_put_contents("app/".$tablename."-update.php", $step9, LOCK_EX)) {
        die("Unable to open file!");
    }
    echo "Generating $tablename Update file<br>";
}

function count_index_colums($table) {
    global $excluded_keys;
    $i = 0;
    foreach ( $_POST as $key => $value) {
        if (in_array($key, $excluded_keys)) {
            //echo "nope";
        }
        else if ($key == $table) {
            foreach ( $_POST[$key] as $columns )
            {
                if (isset($columns['columnvisible'])){
                    $column_visible = $columns['columnvisible'];
                    if ($column_visible == 1) {
                        $i++;
                    }
                }
            }
        }
    }
    return $i;
}

function generate($postdata) {
    // echo "<pre>";
    // print_r($postdata);
    // echo "</pre>";
    // Go trough the POST array
    // Every table is a key
    foreach ($postdata as $key => $value) {
        $tables = array();
        $tablename = '';
        $tabledisplay = '';
        $columnname = '' ;
        $columndisplay = '';
        $columnvisible = '';
        $columns_available = array();
        $index_table_rows = '';
        $index_table_headers = '';
        $read_records = '';

        $create_records = '';
        $create_err_records = '';
        $create_sql_columnnames = array();
        $create_numberofparams = '';
        $create_sql_params = array();
        $create_sqlcolumns = array();
        $create_html = array();
        $create_postvars = '';

        $update_sql_params = array();
        $update_sql_columns = array();
        $update_sql_id = '';
        $update_column_rows = '';

        global $excluded_keys;
        global $sort;
        global $link;
        global $forced_deletion;

        if (!in_array($key, $excluded_keys)) {
            $i = 0;
            $j = 0;
            $max = count_index_colums($key)+1;
            $total_columns = count($_POST[$key]);
            $total_params = count($_POST[$key]);

            //Specific INDEX page variables
            foreach ( $_POST[$key] as $columns ) {
                if (isset($columns['primary'])){
                    $column_id =  $columns['columnname'];
                }

                //INDEXFILE VARIABLES
                //Get the columns visible in the index file
                if (isset($columns['columnvisible'])){
                    $column_visible = $columns['columnvisible'];
                    if ($columns['columnvisible'] == 1 &&  $i < $max) {

                        $columnname = $columns['columnname'];

                        if (!empty($columns['columndisplay'])){
                            $columndisplay = $columns['columndisplay'];
                        } else {
                            $columndisplay = $columns['columnname'];
                        }

                        $columns_available [] = $columnname;
                        $index_table_headers .= 'echo "<th><a href=?search=$search&sort='.$sort.'&order='.$columnname.'&sort=$sort>'.$columndisplay.'</th>";'."\n\t\t\t\t\t\t\t\t\t\t";
                        $index_table_rows .= 'echo "<td>" . highlight($row['. "'" . $columnname . "'" . '],$search) . "</td>";';
                        $i++;
                    }
                }
            }

            //DETAIL CREATE UPDATE AND DELETE pages variables
            foreach ( $_POST[$key] as $columns ) {
                //print_r($columns);
                if ($j < $total_columns) {

                    if (isset($columns['columndisplay'])){
                        $columndisplay = $columns['columndisplay'];
                    }
                    if (empty($columns['columndisplay'])){
                        $columndisplay = $columns['columnname'];
                    }

                    if (!empty($columns['auto'])){
                        //Dont create html input field for auto-increment columns
                        $j++;
                        $total_params--;
                    }

                        //Get all tablenames in an array
                        $tablename = $columns['tablename'];
                        if (!in_array($tablename, $tables))
                        {
                            $tables[$tablename] = $tabledisplay;
                        }

                        $tablename = $columns['tablename'];
                        if (!empty($columns['tabledisplay'])) {
                            $tabledisplay = $columns['tabledisplay'];
                        } else {
                            $tabledisplay = $columns['tablename'];
                        }


                    if(empty($columns['auto'])) {

                        $columnname = $columns['columnname'];
                        $read_records .= '<div class="form-group border border-success">
                            <h4>'.$columndisplay.'</h4>
                            <p class="form-weight-bold px-2"><?php echo $row["'.$columnname.'"]; ?></p>
                        </div>';

                        $create_records .= "\$$columnname = \"\";\n";
                        $create_record = "\$$columnname";
                        $create_err_records .= "\$$columnname".'_err'." = \"\";\n";
                        $create_err_record = "\$$columnname".'_err';
                        $create_sqlcolumns [] = $columnname;
                        $create_sql_params [] = "\$$columnname";
                        $create_postvars .= "$$columnname = trim(\$_POST[\"$columnname\"]);\n\t\t";

                        $update_sql_params [] = "$columnname".'=?';
                        $update_sql_id = "$column_id".'=?';
                        $update_column_rows .= "$$columnname = \$row[\"$columnname\"];\n\t\t\t\t\t";


                        //Foreign Key
                        //Check if there are foreign keys to take into consideration
                        if(!empty($columns['fk'])){
                            //Get the Foreign Key
                            $sql_getfk = "SELECT i.TABLE_NAME as 'Table', k.COLUMN_NAME as 'Column',
                                    k.REFERENCED_TABLE_NAME as 'FK Table', k.REFERENCED_COLUMN_NAME as 'FK Column',
                                    i.CONSTRAINT_NAME as 'Constraint Name'
                                    FROM information_schema.TABLE_CONSTRAINTS i
                                    LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME
                                    WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' AND k.TABLE_NAME = '$tablename' AND k.COLUMN_NAME = '$columnname'";
                            $result = mysqli_query($link, $sql_getfk);
                            if (mysqli_num_rows($result) > 0) {
                            while($row = mysqli_fetch_assoc($result)) {
                                $fk_table = $row["FK Table"];
                                $fk_column = $row["FK Column"];
                            }


                            //Be careful code below is particular regarding single and double quotes.

                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                    <select class="form-control" id="'. $columnname .'" name="'. $columnname .'">
                                    <?php
                                        $sql = "SELECT *,'. $fk_column .' FROM '. $fk_table . '";
                                        $result = mysqli_query($link, $sql);
                                        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                                            array_pop($row);
                                            $value = implode(" | ", $row);
                                            if ($row["' . $fk_column . '"] == $' . $columnname . '){
                                            echo \'<option value="\' . "$row['. $fk_column. ']" . \'"selected="selected">\' . "$value" . \'</option>\';
                                            } else {
                                                echo \'<option value="\' . "$row['. $fk_column. ']" . \'">\' . "$value" . \'</option>\';
                                        }
                                        }
                                    ?>
                                    </select>
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        }

                // No Foreign Keys, just regular columns from here on
                } else {

                        $type = column_type($columns['columntype']);

                        switch($type) {
                        //TEXT
                        case 0:
                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <input type="text" name="'. $columnname .'" class="form-control" value="<?php echo '. $create_record. '; ?>">
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        break;

                        //ENUM types
                        case 2:
                        //Make sure on the update form that the previously selected type is also selected from the list
                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <select name="'.$columnname.'" class="form-control" id="'.$columnname .'">';
                            $create_html [] .=  '<?php
                                            $sql_enum = "SELECT COLUMN_TYPE as AllPossibleEnumValues
                                            FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '. "'$tablename'" .'  AND COLUMN_NAME = '."'$columnname'" .'";
                                            $result = mysqli_query($link, $sql_enum);
                                            while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
                                            preg_match(\'/enum\((.*)\)$/\', $row[0], $matches);
                                            $vals = explode("," , $matches[1]);
                                            foreach ($vals as $val){
                                                $val = substr($val, 1);
                                                $val = rtrim($val, "\'");
                                                if ($val == $'.$columnname.'){
                                                echo \'<option value="\' . $val . \'" selected="selected">\' . $val . \'</option>\';
                                                } else
                                                echo \'<option value="\' . $val . \'">\' . $val . \'</option>\';
                                                        }
                                            }?>';

                            $create_html [] .= '</select>
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                                </div>';
                        break;
                        //VARCHAR
                        case 3:
                            preg_match('#\((.*?)\)#', $columns['columntype'], $match);
                            $maxlength = $match[1];

                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <input type="text" name="'. $columnname .'" maxlength="'.$maxlength.'"class="form-control" value="<?php echo '. $create_record. '; ?>">
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        break;
                        //TINYINT - Will never hit. Needs work.
                        case 4:
                            $regex = "/'(.*?)'/";
                            preg_match_all( $regex , $columns['columntype'] , $enum_array );

                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <select name="'.$columnname.'" class="form-control" id="'.$columnname .'">';
                                        $create_html [] .= '    <option value="0">0</option>';
                                        $create_html [] .= '    <option value="1">1</option>';
                            $create_html [] .= '</select>
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                                </div>';
                        break;
                        //INT
                        case 5:
                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <input type="number" name="'. $columnname .'" class="form-control" value="<?php echo '. $create_record. '; ?>">
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        break;

                        //DECIMAL
                        case 6:
                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <input type="number" name="'. $columnname .'" class="form-control" value="<?php echo '. $create_record. '; ?>" step="any">
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        break;
                        //DATE
                        case 7:
                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <input type="date" name="'. $columnname .'" class="form-control" value="<?php echo '. $create_record. '; ?>">
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        break;
                        //DATETIME
                        case 8:
                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <input type="datetime-local" name="'. $columnname .'" class="form-control" value="<?php echo date("Y-m-d\TH:i:s", strtotime('. $create_record. ')); ?>">
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        break;

                        default:
                            $create_html [] = '<div class="form-group">
                                <label>'.$columndisplay.'</label>
                                <textarea name="'. $columnname .'" class="form-control"><?php echo '. $create_record. ' ; ?></textarea>
                                <span class="form-text"><?php echo ' . $create_err_record . '; ?></span>
                            </div>';
                        break;
                        }
                    }
                        $j++;
                    }
                }
                if ($j == $total_columns) {

                    $update_sql_columns = $create_sql_params;
                    $update_sql_columns [] = "\$$column_id";
                    $update_sql_columns = implode(",", $update_sql_columns);

                    $index_sql_search = implode(",", $columns_available);
                    $create_numberofparams = array_fill(0, $total_params, '?');
                    $create_numberofparams = implode(",", $create_numberofparams);
                    $create_sqlcolumns = implode(",", $create_sqlcolumns);
                    $create_sql_params = implode(",", $create_sql_params);
                    $create_html = implode("\n\t\t\t\t\t\t", $create_html);

                    $update_sql_params = implode(",", $update_sql_params);

                    //Generate everything
                    $start_page = "";

                    foreach($tables as $key => $value) {
                        //echo "$key is at $value";
                        //$start_page .= '<a href="'. $key . '-index.php" class="btn btn-primary" role="button">'. $value. '</a> ';
                        //$button_string = "\t".'<a class="dropdown-item" href="'.$start_page_link.'">'.$td.'</a>'."\n\t".$buttons_delimiter;
                         $start_page .= '<a href="'. $key . '-index.php" class="dropdown-item">'. $value. ' Manager</a> ';
                         $start_page .= '<a href="'. $key . '-index2.php" class="dropdown-item" target="_blank">'. $value. ' Viewer</a> ';
                        $start_page .= "\n\t";
                    }

                    // force existing files deletion
                    if (!$forced_deletion && (!isset($_POST['keep_startpage']) || (isset($_POST['keep_startpage']) && $_POST['keep_startpage'] != 'true'))) {
                        $forced_deletion = true;
                        echo '<h3>Deleting existing files</h3>';
			$keep = array('config.php', 'helpers.php','class.user.php', 'login.php', 'logout.php', 'style.css', 'sign-up.php', 'userauth.php');
                        foreach( glob("app/*") as $file ) {
                            if( !in_array(basename($file), $keep) ){
                                if (unlink($file)) {
                                    echo $file.'<br>';
                                }
                            }
                        }
                        echo '<br>';
                    }

                    generate_navbar($value, $start_page, isset($_POST['keep_startpage']) && $_POST['keep_startpage'] == 'true' ? true : false, isset($_POST['append_links']) && $_POST['append_links'] == 'true' ? true : false, $tabledisplay);
                    generate_error();
                    generate_startpage();
		    generate_userauth();
		    generate_stylesheet();
		    generate_login($tablename);
		    generate_logout();
		    generate_signup($tablename);
                    generate_index($tablename,$tabledisplay,$index_table_headers,$index_table_rows,$column_id, $columns_available,$index_sql_search);
                    generate_index2($tablename,$tabledisplay,$index_table_headers,$index_table_rows,$column_id, $columns_available,$index_sql_search);
                    generate_create($tablename,$create_records, $create_err_records, $create_sqlcolumns, $create_numberofparams, $create_sql_params, $create_html, $create_postvars);
                    generate_read($tablename,$column_id,$read_records);
                    generate_update($tablename, $create_records, $create_err_records, $create_postvars, $column_id, $create_html, $update_sql_params, $update_sql_id, $update_column_rows, $update_sql_columns);
                    generate_delete($tablename,$column_id);
		    generate_export2excel($tablename);
                }
            }

        }

    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <title>Generated pages</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

</head>
<body class="bg-light">
<section class="py-5">
    <div class="container bg-white py-5 shadow">
        <div class="row">
            <div class="col-md-12 mx-auto px-5">
                <?php generate($_POST); ?>
                <hr>
                <br>Your app has been created! It is completely self contained in the /app folder. You can move this folder anywhere on your server.<br><br>
                <a href="app/index.php" target="_blank" rel="noopener noreferrer">Go to your app</a> (this will open your app in a new tab).<br><br>
                You can close this tab or leave it open and use the back button to make changes and regenerate the app. Every run will overwrite the previous app unless you checked the "Keep previously generated startpage" box.<br><br>
                <hr>
                If you need further instructions please visit <a href="http://cruddiy.com">cruddiy.com</a>

            </div>
        </div>
    </div>
</section>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
helpers.php
wget 'https://lists2.roe3.org/cruddiy/helpers.php'
View Content
<?php
// retrieves and enhances postdata table keys and values on CREATE and UPDATE events
function parse_columns($table_name, $postdata) {
    global $link;
    $vars = array();

    // prepare a default return value
    $default = null;

    // get all columns, including the ones not sent by the CRUD form
    $sql = "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, EXTRA
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE table_name = '".$table_name."'";
    $result = mysqli_query($link,$sql);
    while($row = mysqli_fetch_assoc($result))
    {

        $debug = 0;
        if ($debug) {
            echo "<pre>";
            // print_r($postdata);
            echo $row['COLUMN_NAME'] . "\t";
            echo $row['DATA_TYPE'] . "\t";
            echo $row['IS_NULLABLE'] . "\t";
            echo $row['COLUMN_DEFAULT'] . "\t";
            echo $row['EXTRA'] . "\t";
            echo $default . "\n";
            echo "</pre>";
        }

        switch($row['DATA_TYPE']) {

            // fix "Incorrect decimal value: '' error in STRICT_MODE or STRICT_TRANS_TABLE
            // @see https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
            case 'decimal':
                $default = 0;
                break;

            // fix "Incorrect datetime value: '0' " on non-null datetime columns
            // with 'CURRENT_TIMESTAMP' default not being set automatically
            // and refusing to take NULL value
            case 'datetime':
                if ($row['COLUMN_DEFAULT'] != 'CURRENT_TIMESTAMP' && $row['IS_NULLABLE'] == 'YES') {
                    $default = null;
                } else {
                    $default =  date('Y-m-d H:i:s');
                }
                if ($postdata[$row['COLUMN_NAME']] == 'CURRENT_TIMESTAMP') {
                    $_POST[$row['COLUMN_NAME']] =  date('Y-m-d H:i:s');
                }
                break;
        }

        // check that fieldname was set before sending values to pdo
        $vars[$row['COLUMN_NAME']] = isset($_POST[$row['COLUMN_NAME']]) && $_POST[$row['COLUMN_NAME']] ? trim($_POST[$row['COLUMN_NAME']]) : $default;
    }
    return $vars;
}



// get extra attributes for  table keys on CREATE and UPDATE events
function get_columns_attributes($table_name, $column) {
    global $link;
    $sql = "SELECT COLUMN_DEFAULT, COLUMN_COMMENT
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE table_name = '".$table_name."'
            AND column_name = '".$column."'";
    $result = mysqli_query($link,$sql);
    while($row = mysqli_fetch_assoc($result))
    {
        $debug = 0;
        if ($debug) {
            echo "<pre>";
            print_r($row);
            echo "</pre>";
        }
        return $row;
    }
}
?>
relations.php
wget 'https://lists2.roe3.org/cruddiy/relations.php'
View Content
<?php

if(isset($_POST['index'])) {
    
    if((isset($_POST['server'])) && $_POST['server'] <> '') {
        $server=trim($_POST['server']);
    } else {
        $server = "localhost";
    }
	if(isset($_POST['username'])) $username=trim($_POST['username']);
	if(isset($_POST['password'])) $password=trim($_POST['password']);
	if(isset($_POST['database'])) $database=trim($_POST['database']);
	if(isset($_POST['numrecordsperpage'])) $numrecordsperpage=$_POST['numrecordsperpage'];

    if((isset($_POST['appname'])) && $_POST['appname'] <> '') {
        $appname=trim($_POST['appname']);
    } else {
        $appname = "Database Admin";
    }
	/* Attempt to connect to MySQL database */
	$link = mysqli_connect($server, $username, $password, $database);
	// Check connection
	if($link === false)
		die("ERROR: Could not connect. " . mysqli_connect_error());

	/* Clean up User inputs against SQL injection */
	foreach($_POST as $k => $v) {
		$_POST[$k] = mysqli_real_escape_string($link, $v);
	}

	if (!file_exists('app'))
		mkdir('app', 0777, true);


    $helpersfilename = 'helpers.php';
    $handle = fopen('helpers.php', "r") or die("Unable to open Helpers file! Please check your file permissions.");;
    $helpers = fread($handle, filesize($helpersfilename));
    fclose($handle);

    $helpersfile = fopen("app/".$helpersfilename, "w") or die("Unable to create Helpers file! Please check your file permissions");
    fwrite($helpersfile, $helpers);
	fclose($helpersfile);

    $classfile = fopen("app/class.user.php","w") or die("Unable to open class.user.php file!");
        $txt2  = "<?php \n\n";
        $txt2 .= "class USER \n";
        $txt2 .= "{ \n";
        $txt2 .= "    private \$db; \n\n";
 
        $txt2 .= "function __construct(\$DB_con) \n";
        $txt2 .= "{ \n";
        $txt2 .= "\$this->db = \$DB_con; \n";
        $txt2 .= "} \n\n";
 
        $txt2 .= "public function register(\$fname,\$lname,\$uname,\$umail,\$upass) \n";
        $txt2 .= "{ \n";
        $txt2 .= "try \n";
        $txt2 .= "{ \n";
        $txt2 .= "\$new_password = password_hash(\$upass, PASSWORD_DEFAULT); \n\n";
   
        $txt2 .= "\$stmt = \$this->db->prepare(\"INSERT INTO users_table(user_name,user_email,user_pass)VALUES(:uname, :umail, :upass)\"); \n\n";
              
        $txt2 .= "\$stmt->bindparam(\":uname\", \$uname); \n";
        $txt2 .= "\$stmt->bindparam(\":umail\", \$umail); \n";
        $txt2 .= "\$stmt->bindparam(\":upass\", \$new_password);  \n";           
        $txt2 .= "\$stmt->execute();  \n\n";
   
        $txt2 .= "return \$stmt;  \n";
        $txt2 .= "} \n";
        $txt2 .= "catch(PDOException \$e) \n";
        $txt2 .= "{ \n";
        $txt2 .= "echo \$e->getMessage(); \n\n";
        $txt2 .= "} \n";
    $txt2 .= "} \n\n";
 
    $txt2 .= "public function login(\$uname,\$umail,\$upass) \n";
    $txt2 .= "{ \n";
    $txt2 .= "   try \n";
    $txt2 .= "   { \n";
    $txt2 .= "      \$stmt = \$this->db->prepare(\"SELECT * FROM users_table WHERE user_name=:uname OR user_email=:umail LIMIT 1\"); \n";
    $txt2 .= "      \$stmt->execute(array(':uname'=>\$uname, ':umail'=>\$umail)); \n";
    $txt2 .= "      \$userRow=\$stmt->fetch(PDO::FETCH_ASSOC); \n";
    $txt2 .= "      if(\$stmt->rowCount() > 0) \n";
    $txt2 .= "     { \n";
    $txt2 .= "         if(password_verify(\$upass, \$userRow['user_pass'])) \n";
    $txt2 .= "         { \n";
    $txt2 .= "           \$_SESSION['user_session'] = \$userRow['user_id']; \n";
    $txt2 .= "            return true; \n";
    $txt2 .= "         } \n";
    $txt2 .= "         else \n";
    $txt2 .= "         { \n";
    $txt2 .= "            return false; \n";
    $txt2 .= "         } \n";
    $txt2 .= "     } \n";
    $txt2 .= "   } \n";
    $txt2 .= "   catch(PDOException \$e) \n";
    $txt2 .= "   { \n";
    $txt2 .= "       echo \$e->getMessage(); \n";
    $txt2 .= "   } \n";
    $txt2 .= "} \n\n";
 
    $txt2 .= "public function is_loggedin() \n";
    $txt2 .= "{ \n";
    $txt2 .= "  if(isset(\$_SESSION['user_session'])) \n";
    $txt2 .= "  { \n";
    $txt2 .= "     return true; \n";
    $txt2 .= "  } \n";
    $txt2 .= "} \n\n";
 
   $txt2 .= "public function redirect(\$url) \n";
   $txt2 .= "{ \n";
   $txt2 .= "    header(\"Location: \$url\"); \n";
   $txt2 .= "} \n\n";
 
   $txt2 .= "public function logout() \n";
   $txt2 .= "{ \n";
   $txt2 .= "     session_destroy(); \n";
   $txt2 .= "     unset(\$_SESSION['user_session']); \n";
   $txt2 .= "     return true; \n";
   $txt2 .= "} \n";
   $txt2 .= "} \n";
   $txt2 .= "?> \n";
  fwrite($classfile,$txt2);
  fclose($classfile);

	$configfile = fopen("app/config.php", "w") or die("Unable to open Config file!");
	$txt  = "<?php \n";
	$txt .= "\$db_server = '$server'; \n";
	$txt .= "\$db_name = '$database'; \n";
	$txt .= "\$db_user = '$username'; \n";
	$txt .= "\$db_password = '$password'; \n";
	$txt .= "\$no_of_records_per_page = $numrecordsperpage; \n";
	$txt .= "\$appname = '$appname'; \n\n";
	$txt .= "\$link = mysqli_connect(\$db_server, \$db_user, \$db_password, \$db_name); \n";

    $txt .= '$query = "SHOW VARIABLES LIKE \'character_set_database\'";' ."\n";
    $txt .= 'if ($result = mysqli_query($link, $query)) {' ."\n";
    $txt .= '    while ($row = mysqli_fetch_row($result)) {' ."\n";
    $txt .= '        if (!$link->set_charset($row[1])) {' ."\n";
    $txt .= '            printf("Error loading character set $row[1]: %s\n", $link->error);' ."\n";
    $txt .= '            exit();' ."\n";
    $txt .= '        } else {' ."\n";
    $txt .= '            // printf("Current character set: %s", $link->character_set_name());' ."\n";
    $txt .= '        }' ."\n";
    $txt .= '    }' ."\n";
    $txt .= '}' ."\n";

    $txt .= 'try' ."\n";
    $txt .= '{' ."\n\n";
    $txt .= "\$DB_con = new PDO(\"mysql:host={\$db_server};dbname={\$db_name}\",\$db_user,\$db_password);  \n";
    $txt .= "\$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); \n";
    $txt .= '}' ."\n";
    $txt .= 'catch(PDOException $e)' ."\n";
    $txt .= '{' ."\n";
    $txt .= '     echo $e->getMessage();' ."\n";
    $txt .= '}' ."\n\n";

    $txt .= "include_once 'class.user.php';" ."\n";
    $txt .= "\$user = new USER(\$DB_con); \n\n";

	$txt .= "\n?>";
	fwrite($configfile, $txt);
	fclose($configfile);

}

/* CREATE NEW DATABASE TABLE FOR LOGIN PANEL */

$tablequery = "SHOW TABLES LIKE	'users_table'";
$tableresult = mysqli_query($link,$tablequery);
    if(mysqli_num_rows($tableresult) == 1) {
        echo "Login Users Table Already Exists<br/><hr>";
  } else {

  echo "Creating Login Users Table in Database . . . <br/><hr>";

  $createtablequery1 = "
  DROP TABLE IF EXISTS users_table
  ";
  
  $createtablequery2 = "
  CREATE TABLE users_table (
     user_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
     user_name VARCHAR(255) NOT NULL,
     user_email VARCHAR(60) NOT NULL,
     user_pass VARCHAR(255) NOT NULL,
     UNIQUE (user_name),
     UNIQUE (user_email)
  )";
  
  $createtablequery3 = "
  INSERT INTO users_table 
  (user_id,user_name,user_email,user_pass) 
  VALUES (1,'test','test@test.com','$2y$10$0Vld430LT/HkQFKr4k857.X6l3GlE1AthUhVv7KW32I6iRRt36BLW')
  ";
  
  if (mysqli_query($link, $createtablequery1)) {
    echo "Users Table Successfully Dropped If Existing Previously<br/>";
  } else {
    echo "Error dropping table: " . mysqli_error($link);
  }
  
  if (mysqli_query($link, $createtablequery2)) {
    echo "Users Table Created Successfully<br/>";
  } else {
    echo "Error creating table: " . mysqli_error($link);
  }
  
  if (mysqli_query($link, $createtablequery3)) {
    echo "Users Table Populated With Test Data (test:123456)<br/>";
  } else {
    echo "Error inserting data: " . mysqli_error($link);
  }
}

require "app/config.php";

if(isset($_POST['submit'])){
    $tablename = $_POST['tablename'];
    $fkname = $_POST['fkname'];

    $sql = "ALTER TABLE $tablename DROP FOREIGN KEY $fkname";
    if ($result = mysqli_query($link, $sql)) {
        echo "The foreign_key '$fkname' was deleted from '$tablename'";
    } else {
        echo("Something went wrong. Error description: " . mysqli_error($link));
    }
}

if(isset($_POST['addkey'])){
    $primary = $_POST['primary'];  
    $fk = $_POST['fk'];

    $split_primary=explode('|', $primary);
    $split_fk=explode('|', $fk);

    $fk_name = $split_fk[0].'_ibfk_1';

    $ondel_val = $_POST['ondelete'];
    $onupd_val = $_POST['onupdate'];

    switch ($ondel_val) {
        case "cascade":
           $ondel = "ON DELETE CASCADE";
            break;
        case "setnull":
            $ondel = "ON DELETE SET NULL";
            break;
       case "restrict":
           $ondel = "ON DELETE RESTRICT";
           break;
       default:
           $ondel = "";
    }

    switch ($onupd_val) {
        case "cascade":
           $onupd = "ON UPDATE CASCADE";
            break;
        case "setnull":
            $onupd = "ON UPDATE SET NULL";
            break;
       case "restrict":
            $onupd = "ON UPDATE RESTRICT";
            break;
       default:
            $onupd = "";
    }

    $sql = "ALTER TABLE $split_fk[0] ADD FOREIGN KEY $fk_name ($split_fk[1]) REFERENCES $split_primary[0]($split_primary[1]) $ondel $onupd;";

    if ($result = mysqli_query($link, $sql)) {
        echo "The foreign_key '$fk_name' was created from ' $split_fk[0]($split_fk[1])' to '$split_primary[0]($split_primary[1])'.";
    } else {
         echo("Something went wrong. Error description: " . mysqli_error($link));
    }
}

?>
<!doctype html>
<html lang="en">
<head>
    <title>Select Relations</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="cruddiy.css">
</head>
<body>
<section class="py-5">
    <div class="container" style='max-width:75%'>
        <div class="row">
            <div class="col-md-12 mx-auto">
                <div class="text-center">
                    <h4 class="mb-0">Existing Table Relations</h4><br>
                    <fieldset>
                        <table class="table table-bordered">
                          <thead>
                            <tr>
                              <?php
                                $sql = "SELECT i.TABLE_NAME as 'Table Name', k.COLUMN_NAME as 'Foreign Key', 
                                    k.REFERENCED_TABLE_NAME as 'Primary Table', k.REFERENCED_COLUMN_NAME as 'Primary Key',
                                    i.CONSTRAINT_NAME as 'Constraint Name', 'Delete' as 'Delete' 
                                        FROM information_schema.TABLE_CONSTRAINTS i
                                        LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME
                                        WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' AND i.TABLE_SCHEMA = DATABASE()";
                                if (($result = mysqli_query($link, $sql)) && $result->num_rows > 0) {
                                    $row = mysqli_fetch_assoc($result);
                                    foreach ($row as $col => $value) {
                                        echo "<th>";
                                        echo $col;
                                        echo "</th>"; 
									}
									echo "</thead><tbody>";
									mysqli_data_seek($result, 0);
									while($row = mysqli_fetch_array($result))
									{
										echo "<tr>";
										echo "<td>" . $row['Table Name'] . "</td>";
										echo "<td>" . $row['Foreign Key'] . "</td>";
										echo "<td>" . $row['Primary Table'] . "</td>";
										echo "<td>" . $row['Primary Key'] . "</td>";
										echo "<td>" . $row['Constraint Name'] . "</td>";
										echo "<td class='fk-delete'>";
										?><form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
										<?php
												echo '<input type="hidden" name="tablename" value="';
												echo $row['Table Name'] .'">';
												echo '<input type="hidden" name="fkname" value="';
												echo $row['Constraint Name'] . '">';
												echo "<button type='submit' id='singlebutton' name='submit' class='btn btn-danger'>Delete</button>"; 
												echo "</form></td>";
												echo "</tr>";
									}
								} else echo "</thead><tbody><tr><td>No relations found</td></tr>";
                            ?>
                                </tbody>
                                </table> 
                <div class="text-center">
                    <h4 class="mb-0">Add New Table Relation</h4><br>
                      <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
                        $sql = "select TABLE_NAME as TableName, COLUMN_NAME as ColumnName from information_schema.columns where table_schema = '$db_name'";
                        $result = mysqli_query($link,$sql);
                        echo "<label>This column:</label>
                            <select name='fk' id='fk' style='max-width:20%;'><br>";
                        while ($column = mysqli_fetch_array($result)) {
                            echo '<option name="'.$column[0]. '|'.$column[1]. '  " value="'.$column[0].'|'.$column[1]. '">'.$column[0].' ('.$column[1].')</option>';
                        }
                        echo '</select>';

                        mysqli_free_result($result);
                        $result = mysqli_query($link,$sql);
                        echo "<label>has a foreign key relation to:</label>
                            <select name='primary' id='primary' style='max-width:20%'>";
                        while ($column = mysqli_fetch_array($result)) {
                            echo '<option name="'.$column[0]. '|'.$column[1]. '  " value="'.$column[0].'|'.$column[1]. '">'.$column[0].' ('.$column[1].')</option>';

                        }
                        echo '</select>';
?>
                       <select name='ondelete' id='ondelete' style='max-width:15%'>";
                            <option name="ondelete_action" value="">Pick action</option>
                            <option name="ondelete_cascade" value="cascade">On Delete: Cascade</option>
                            <option name="ondelete_setnull" value="setnull">On Delete: Set Null</option>
                            <option name="ondelete_restrict" value="restrict">On Delete: Restrict</option>
                       </select>

                       <select name='onupdate' id='onupdate' style='max-width:15%'>";
                            <option name="onupdate_action" value="">Pick action</option>
                            <option name="onupdate_cascade" value="cascade">On Update: Cascade</option>
                            <option name="onupdate_setnull" value="setnull">On Update: Set Null</option>
                            <option name="onupdate_restrict" value="restrict">On Update: Restrict</option>
                       </select>
                                <label class="col-form-label mt-3" for="singlebutton"></label>
                                <button type="submit" id="singlebutton" name="addkey" class="btn btn-primary">Create relation</button>
                    </fieldset>
                </form>
            </div>
        </div>
    </div>
<hr>
On this page you can add new or delete existing table relations i.e. foreign keys. Having foreign keys will result in Cruddiy forms with cascading deletes/updates and dropdown fields populated by foreign keys. If it is not clear what you want or need to do here, it is SAFER to skip this step and move to the next step! You can always come back later and regenerate new forms.
<hr>
<form method="post" action="tables.php">
    <button type="submit" id="singlebutton" name="singlebutton" class="btn btn-success">Continue CRUD Creation Process</button>
</form>     
</section>

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>

tables.php
wget 'https://lists2.roe3.org/cruddiy/tables.php'
View Content
    <?php
        include "app/config.php";
    ?>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>CRUD generator</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    </head>
    <body class="bg-light">
    <section class="pt-5">
        <div class="container bg-white shadow py-5">
            <div class="row">
            <div class="col-md-12 mx-auto">
                    <div class="text-center mb-4">
                        <h4 class="h1 border-bottom pb-2">All Available Tables</h4>
                    </div>

                    <div class="row align-items-center mb-1">
                        <div class="col-md-11 text-right pr-5 ml-3">
                            <input type="checkbox" id="checkall">
                            <label for="checkall">Check/uncheck all</label>
                        </div>
                    </div>


                    <form class="form-horizontal" action="columns.php" method="post">
                        <fieldset>
                            <?php
                            //Get all tables
                            $tablelist = array();
                            $res = mysqli_query($link,"SHOW TABLES");
                            while($cRow = mysqli_fetch_array($res))
                            {
                                $tablelist[] = $cRow[0];
                            }

                            //Loop trough list of tables
                            $i = 0;
                            foreach($tablelist as $table) {

                                echo
                        '<div class="row align-items-center">
                            <div class="col-md-3 text-right">
                                  <label class="control-label" for="table['.$i.'][tablename]">'. $table . ' </label>
                            </div>
                            <div class="col-md-6">
                                     <input type="hidden" name="table['.$i.'][tablename]" value="'.$table.'"/>
                                     <input id="textinput_'.$table. '" name="table['.$i.'][tabledisplay]" type="text" placeholder="Display table name in frontend" class="form-control rounded-0 shadow-sm">
                            </div>
                            <div class="col-md-3">
                              <input class="mr-1" type="checkbox"  name="table['.$i.'][tablecheckbox]" id="checkboxes-'.$i.'" value="1"><label for="checkboxes-'.$i.'">Generate CRUD</label>
                            </div>
                        </div>
                        ';

                                $i++;
                            }
                            ?>
                            <div class="row">
                                <div class="col-md-6 mx-auto">
                                    <label class="control-label" for="singlebutton"></label>
                                    <button type="submit" id="singlebutton" name="singlebutton" class="btn btn-success btn-block shadow rounded-0">Select columns from tables</button>
                                </div>
                            </div>
                        </fieldset>
                    </form>
                </div>
            </div>
        </div>
    </section>
    <br>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <script>
    $(document).ready(function () {
        $('#checkall').click(function(e) {
            var chb = $('.form-horizontal').find('input[type="checkbox"]');
            chb.prop('checked', !chb.prop('checked'));
        });
    });
    </script>
    </body>
    </html>
templates.php
wget 'https://lists2.roe3.org/cruddiy/templates.php'
View Content
<?php

$indexfile = <<<'EOT'
<?php 
@session_start();
if ($_SERVER["SERVER_PORT"]!=443){ header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); exit(); }

 require_once "config.php";
 require_once "helpers.php";
// require_once "userauth.php";

if(!isset($_SESSION['user_session'])) {
   header('Location: login.php');
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{APP_NAME}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <script src="https://kit.fontawesome.com/6b773fe9e4.js" crossorigin="anonymous"></script>
    <style type="text/css">
        .page-header h2{
            margin-top: 0;
        }
        table tr td:last-child a{
            margin-right: 5px;
        }
        body {
            font-size: 14px;
        }
    </style>
</head>
<?php require_once('navbar.php'); ?>
<body>
    <section class="pt-5">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="page-header clearfix">
                        <h2 class="float-left">{TABLE_DISPLAY} Details</h2>
			<a href="export.php" class="btn btn-success float-right">Export to Excel</a>
                        <a href="{TABLE_NAME}-create.php" class="btn btn-success float-right mr-2">Add New Record</a>
                        <a href="{TABLE_NAME}-index.php" class="btn btn-info float-right mr-2">Reset View</a>
                        <a href="index.php" class="btn btn-secondary float-right mr-2">Back</a>
                    </div>

                    <div class="form-row">
                        <form action="{TABLE_NAME}-index.php" method="get">
                        <div class="col">
		            <span>Type in your search term and hit enter.<br/>
		            Click the empty search box and hit enter to restore the full listing.</span>
                          <input type="text" class="form-control" placeholder="Search this table" name="search">
			<?php 
				if(isset($_REQUEST["search"])) {
				  echo "<span>You searched for <b>".$_REQUEST["search"]."</b></span>";
				}
			?>
                        </div>
                    </div>
                        </form>
                    <br>

                    <?php
		// Highlight Matched Keywords
		function highlight($text, $word){
		    $text = preg_replace('#'. preg_quote($word) .'#i', '<span style="background-color: #F9F902;">\\0</span>', $text);
		    return $text;
		}

                    //Get current URL and parameters for correct pagination
                    $protocol = $_SERVER['SERVER_PROTOCOL'];
                    $domain     = $_SERVER['HTTP_HOST'];
                    $script   = $_SERVER['SCRIPT_NAME'];
                    $parameters   = $_GET ? $_SERVER['QUERY_STRING'] : "" ;
                    $protocol=strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')
                                === FALSE ? 'http' : 'https';
                    //$currenturl = $protocol . '://' . $domain. $script . '?' . $parameters;
                    $currenturl = $script . '?' . $parameters;

                    //Pagination
                    if (isset($_GET['pageno'])) {
                        $pageno = $_GET['pageno'];
                    } else {
                        $pageno = 1;
                    }

                    //$no_of_records_per_page is set on the index page. Default is 10.
                    $offset = ($pageno-1) * $no_of_records_per_page;

                    $total_pages_sql = "SELECT COUNT(*) FROM {TABLE_NAME}";
                    $result = mysqli_query($link,$total_pages_sql);
                    $total_rows = mysqli_fetch_array($result)[0];
                    $total_pages = ceil($total_rows / $no_of_records_per_page);

                    //Column sorting on column name
                    $orderBy = array('{COLUMNS}');
                    $order = '{COLUMN_ID}';
                    if (isset($_GET['order']) && in_array($_GET['order'], $orderBy)) {
                            $order = $_GET['order'];
                        }

                    //Column sort order
                    $sortBy = array('asc', 'desc'); $sort = 'desc';
                    if (isset($_GET['sort']) && in_array($_GET['sort'], $sortBy)) {
                          if($_GET['sort']=='asc') {
                            $sort='desc';
                            }
                    else {
                        $sort='asc';
                        }
                    }

                    // Attempt select query execution
                    $sql = "{INDEX_QUERY} ORDER BY $order $sort LIMIT $offset, $no_of_records_per_page";
                    $count_pages = "{INDEX_QUERY}";


                    if(!empty($_GET['search'])) {
                        $search = ($_GET['search']);
                        $sql = "SELECT * FROM {TABLE_NAME}
                            WHERE CONCAT_WS ({INDEX_CONCAT_SEARCH_FIELDS})
                            LIKE '%$search%'
                            ORDER BY $order $sort
                            LIMIT $offset, $no_of_records_per_page";
                        $count_pages = "SELECT * FROM {TABLE_NAME}
                            WHERE CONCAT_WS ({INDEX_CONCAT_SEARCH_FIELDS})
                            LIKE '%$search%'
                            ORDER BY $order $sort";
                    }
                    else {
                        $search = "";
                    }

                    if($result = mysqli_query($link, $sql)){
                        if(mysqli_num_rows($result) > 0){
                            if ($result_count = mysqli_query($link, $count_pages)) {
                               $total_pages = ceil(mysqli_num_rows($result_count) / $no_of_records_per_page);
                           }
                            $number_of_results = mysqli_num_rows($result_count);
                            echo " " . $number_of_results . " results - Page " . $pageno . " of " . $total_pages;

                            echo "<table class='table table-bordered table-striped'>";
                                echo "<thead>";
                                    echo "<tr>";
                                        {INDEX_TABLE_HEADERS}
                                        echo "<th>Action</th>";
                                    echo "</tr>";
                                echo "</thead>";
                                echo "<tbody>";
                                while($row = mysqli_fetch_array($result)){
                                    echo "<tr>";
                                    {INDEX_TABLE_ROWS}
                                        echo "<td>";
                                            echo "<a href='{TABLE_NAME}-read.php?{COLUMN_ID}=". $row['{COLUMN_NAME}'] ."' title='View Record' data-toggle='tooltip'><i class='far fa-eye'></i></a>";
                                            echo "<a href='{TABLE_NAME}-update.php?{COLUMN_ID}=". $row['{COLUMN_NAME}'] ."' title='Update Record' data-toggle='tooltip'><i class='far fa-edit'></i></a>";
                                            echo "<a href='{TABLE_NAME}-delete.php?{COLUMN_ID}=". $row['{COLUMN_NAME}'] ."' title='Delete Record' data-toggle='tooltip'><i class='far fa-trash-alt'></i></a>";
                                        echo "</td>";
                                    echo "</tr>";
                                }
                                echo "</tbody>";
                            echo "</table>";
?>
                                <ul class="pagination" align-right>
                                <?php
                                    $new_url = preg_replace('/&?pageno=[^&]*/', '', $currenturl);
                                 ?>
                                    <li class="page-item"><a class="page-link" href="<?php echo $new_url .'&pageno=1' ?>">First</a></li>
                                    <li class="page-item <?php if($pageno <= 1){ echo 'disabled'; } ?>">
                                        <a class="page-link" href="<?php if($pageno <= 1){ echo '#'; } else { echo $new_url ."&pageno=".($pageno - 1); } ?>">Prev</a>
                                    </li>
                                    <li class="page-item <?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
                                        <a class="page-link" href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo $new_url . "&pageno=".($pageno + 1); } ?>">Next</a>
                                    </li>
                                    <li class="page-item <?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
                                        <a class="page-item"><a class="page-link" href="<?php echo $new_url .'&pageno=' . $total_pages; ?>">Last</a>
                                    </li>
                                </ul>
<?php
                            // Free result set
                            mysqli_free_result($result);
                        } else{
                            echo "<p class='lead'><em>No records were found.</em></p>";
                        }
                    } else{
                        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
                    }

                    // Close connection
                    mysqli_close($link);
                    ?>
                </div>
            </div>
        </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>
</body>
</html>
EOT;

$index2file = <<<'EOT'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{APP_NAME}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <script src="https://kit.fontawesome.com/6b773fe9e4.js" crossorigin="anonymous"></script>
    <style type="text/css">
        .page-header h2{
            margin-top: 0;
        }
        table tr td:last-child a{
            margin-right: 5px;
        }
        body {
            font-size: 14px;
        }
    </style>
</head>
<body>
    <section class="pt-5">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="page-header clearfix">
                        <h2 class="float-left">{TABLE_DISPLAY} Details</h2>
			<a href="export.php" class="btn btn-success float-right">Export to Excel</a>
                        <a href="{TABLE_NAME}-index2.php" class="btn btn-info float-right mr-2">Reset View</a>
                    </div>

                    <div class="form-row">
                        <form action="{TABLE_NAME}-index2.php" method="get">
                        <div class="col">
		            <span>Type in your search term and hit enter.<br/>
		            Click the empty search box and hit enter to restore the full listing.</span>
                          <input type="text" class="form-control" placeholder="Search this table" name="search">
			<?php 
				if(isset($_REQUEST["search"])) {
				  echo "<span>You searched for <b>".$_REQUEST["search"]."</b></span>";
				}
			?>
                        </div>
                    </div>
                        </form>
                    <br>


                    <?php
                    // Include config file
                    require_once "config.php";
                    require_once "helpers.php";

		// Highlight Matched Keywords
		function highlight($text, $word){
		    $text = preg_replace('#'. preg_quote($word) .'#i', '<span style="background-color: #F9F902;">\\0</span>', $text);
		    return $text;
		}

                    //Get current URL and parameters for correct pagination
                    $protocol = $_SERVER['SERVER_PROTOCOL'];
                    $domain     = $_SERVER['HTTP_HOST'];
                    $script   = $_SERVER['SCRIPT_NAME'];
                    $parameters   = $_GET ? $_SERVER['QUERY_STRING'] : "" ;
                    $protocol=strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')
                                === FALSE ? 'http' : 'https';
                    //$currenturl = $protocol . '://' . $domain. $script . '?' . $parameters;
                    $currenturl = $script . '?' . $parameters;

                    //Pagination
                    if (isset($_GET['pageno'])) {
                        $pageno = $_GET['pageno'];
                    } else {
                        $pageno = 1;
                    }

                    //$no_of_records_per_page is set on the index page. Default is 10.
                    $offset = ($pageno-1) * $no_of_records_per_page;

                    $total_pages_sql = "SELECT COUNT(*) FROM {TABLE_NAME}";
                    $result = mysqli_query($link,$total_pages_sql);
                    $total_rows = mysqli_fetch_array($result)[0];
                    $total_pages = ceil($total_rows / $no_of_records_per_page);

                    //Column sorting on column name
                    $orderBy = array('{COLUMNS}');
                    $order = '{COLUMN_ID}';
                    if (isset($_GET['order']) && in_array($_GET['order'], $orderBy)) {
                            $order = $_GET['order'];
                        }

                    //Column sort order
                    $sortBy = array('asc', 'desc'); $sort = 'desc';
                    if (isset($_GET['sort']) && in_array($_GET['sort'], $sortBy)) {
                          if($_GET['sort']=='asc') {
                            $sort='desc';
                            }
                    else {
                        $sort='asc';
                        }
                    }

                    // Attempt select query execution
                    $sql = "{INDEX_QUERY} ORDER BY $order $sort LIMIT $offset, $no_of_records_per_page";
                    $count_pages = "{INDEX_QUERY}";


                    if(!empty($_GET['search'])) {
                        $search = ($_GET['search']);
                        $sql = "SELECT * FROM {TABLE_NAME}
                            WHERE CONCAT_WS ({INDEX_CONCAT_SEARCH_FIELDS})
                            LIKE '%$search%'
                            ORDER BY $order $sort
                            LIMIT $offset, $no_of_records_per_page";
                        $count_pages = "SELECT * FROM {TABLE_NAME}
                            WHERE CONCAT_WS ({INDEX_CONCAT_SEARCH_FIELDS})
                            LIKE '%$search%'
                            ORDER BY $order $sort";
                    }
                    else {
                        $search = "";
                    }

                    if($result = mysqli_query($link, $sql)){
                        if(mysqli_num_rows($result) > 0){
                            if ($result_count = mysqli_query($link, $count_pages)) {
                               $total_pages = ceil(mysqli_num_rows($result_count) / $no_of_records_per_page);
                           }
                            $number_of_results = mysqli_num_rows($result_count);
                            echo " " . $number_of_results . " results - Page " . $pageno . " of " . $total_pages;

                            echo "<table class='table table-bordered table-striped'>";
                                echo "<thead>";
                                    echo "<tr>";
                                        {INDEX_TABLE_HEADERS}
                                    echo "</tr>";
                                echo "</thead>";
                                echo "<tbody>";
                                while($row = mysqli_fetch_array($result)){
                                    echo "<tr>";
                                    {INDEX_TABLE_ROWS}
                                    echo "</tr>";
                                }
                                echo "</tbody>";
                            echo "</table>";
?>
                                <ul class="pagination" align-right>
                                <?php
                                    $new_url = preg_replace('/&?pageno=[^&]*/', '', $currenturl);
                                 ?>
                                    <li class="page-item"><a class="page-link" href="<?php echo $new_url .'&pageno=1' ?>">First</a></li>
                                    <li class="page-item <?php if($pageno <= 1){ echo 'disabled'; } ?>">
                                        <a class="page-link" href="<?php if($pageno <= 1){ echo '#'; } else { echo $new_url ."&pageno=".($pageno - 1); } ?>">Prev</a>
                                    </li>
                                    <li class="page-item <?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
                                        <a class="page-link" href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo $new_url . "&pageno=".($pageno + 1); } ?>">Next</a>
                                    </li>
                                    <li class="page-item <?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
                                        <a class="page-item"><a class="page-link" href="<?php echo $new_url .'&pageno=' . $total_pages; ?>">Last</a>
                                    </li>
                                </ul>
<?php
                            // Free result set
                            mysqli_free_result($result);
                        } else{
                            echo "<p class='lead'><em>No records were found.</em></p>";
                        }
                    } else{
                        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
                    }

                    // Close connection
                    mysqli_close($link);
                    ?>
                </div>
            </div>
        </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>
</body>
</html>
EOT;


$readfile = <<<'EOT'
<?php
// Check existence of id parameter before processing further
$_GET["{TABLE_ID}"] = trim($_GET["{TABLE_ID}"]);
if(isset($_GET["{TABLE_ID}"]) && !empty($_GET["{TABLE_ID}"])){
    // Include config file
    require_once "config.php";
    require_once "helpers.php";

    // Prepare a select statement
    $sql = "SELECT * FROM {TABLE_NAME} WHERE {TABLE_ID} = ?";

    if($stmt = mysqli_prepare($link, $sql)){
        // Set parameters
        $param_id = trim($_GET["{TABLE_ID}"]);

        // Bind variables to the prepared statement as parameters
		if (is_int($param_id)) $__vartype = "i";
		elseif (is_string($param_id)) $__vartype = "s";
		elseif (is_numeric($param_id)) $__vartype = "d";
		else $__vartype = "b"; // blob
        mysqli_stmt_bind_param($stmt, $__vartype, $param_id);

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            $result = mysqli_stmt_get_result($stmt);

            if(mysqli_num_rows($result) == 1){
                /* Fetch result row as an associative array. Since the result set
                contains only one row, we don't need to use while loop */
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
            } else{
                // URL doesn't contain valid id parameter. Redirect to error page
                header("location: error.php");
                exit();
            }

        } else{
            echo "Oops! Something went wrong. Please try again later.<br>".$stmt->error;
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);

    // Close connection
    mysqli_close($link);
} else{
    // URL doesn't contain id parameter. Redirect to error page
    header("location: error.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<?php require_once('navbar.php'); ?>
<body>
    <section class="pt-5">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6 mx-auto border border-danger">
                    <div class="page-header">
                        <h2 style="color:Tomato">View Database Record</h2>
                    </div>

                     {RECORDS_READ_FORM}

                    <p><a href="{TABLE_NAME}-index.php" class="btn btn-primary">Back</a></p>
                </div>
            </div>
        </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
EOT;


$deletefile = <<<'EOT'
<?php
// Process delete operation after confirmation
if(isset($_POST["{TABLE_ID}"]) && !empty($_POST["{TABLE_ID}"])){
    // Include config file
    require_once "config.php";
    require_once "helpers.php";

    // Prepare a delete statement
    $sql = "DELETE FROM {TABLE_NAME} WHERE {TABLE_ID} = ?";

    if($stmt = mysqli_prepare($link, $sql)){
        // Set parameters
        $param_id = trim($_POST["{TABLE_ID}"]);

        // Bind variables to the prepared statement as parameters
		if (is_int($param_id)) $__vartype = "i";
		elseif (is_string($param_id)) $__vartype = "s";
		elseif (is_numeric($param_id)) $__vartype = "d";
		else $__vartype = "b"; // blob
        mysqli_stmt_bind_param($stmt, $__vartype, $param_id);

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            // Records deleted successfully. Redirect to landing page
            header("location: {TABLE_NAME}-index.php");
            exit();
        } else{
            echo "Oops! Something went wrong. Please try again later.<br>".$stmt->error;
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);

    // Close connection
    mysqli_close($link);
} else{
    // Check existence of id parameter
	$_GET["{TABLE_ID}"] = trim($_GET["{TABLE_ID}"]);
    if(empty($_GET["{TABLE_ID}"])){
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<?php require_once('navbar.php'); ?>
<body>
    <section class="pt-5">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6 mx-auto">
                    <div class="page-header">
                        <h1>Delete Record</h1>
                    </div>
                    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
                        <div class="alert alert-danger fade-in">
                            <input type="hidden" name="{TABLE_ID}" value="<?php echo trim($_GET["{TABLE_ID}"]); ?>"/>
                            <p>Are you sure you want to delete this record?</p><br>
                            <p>
                                <input type="submit" value="Yes" class="btn btn-danger">
                                <a href="{TABLE_NAME}-index.php" class="btn btn-secondary">No</a>
                            </p>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>

EOT;

$createfile = <<<'EOT'
<?php
// Include config file
require_once "config.php";
require_once "helpers.php";

// Define variables and initialize with empty values
{CREATE_RECORDS}
{CREATE_ERR_RECORDS}

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
        {CREATE_POST_VARIABLES}

        $dsn = "mysql:host=$db_server;dbname=$db_name;charset=utf8mb4";
        $options = [
          PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
          PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
        ];
        try {
          $pdo = new PDO($dsn, $db_user, $db_password, $options);
        } catch (Exception $e) {
          error_log($e->getMessage());
          exit('Something weird happened'); //something a user can understand
        }

        $vars = parse_columns('{TABLE_NAME}', $_POST);
        $stmt = $pdo->prepare("INSERT INTO {TABLE_NAME} ({CREATE_COLUMN_NAMES}) VALUES ({CREATE_QUESTIONMARK_PARAMS})");

        if($stmt->execute([ {CREATE_SQL_PARAMS}  ])) {
                $stmt = null;
                header("location: {TABLE_NAME}-index.php");
            } else{
                echo "Something went wrong. Please try again later.";
            }

}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<?php require_once('navbar.php'); ?>
<body>
    <section class="pt-5">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6 mx-auto border border-danger">
                    <div class="page-header">
                        <h2>Create Database Record</h2>
                    </div>
                    <p>Please fill this form and submit to add a record to the database.</p>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">

                        {CREATE_HTML}

                        <input type="submit" class="btn btn-primary" value="Submit">
                        <a href="{TABLE_NAME}-index.php" class="btn btn-secondary">Cancel</a>
                    </form>
                </div>
            </div>
        </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
EOT;


$updatefile = <<<'EOT'
<?php
// Include config file
require_once "config.php";
require_once "helpers.php";

// Define variables and initialize with empty values
{CREATE_RECORDS}
{CREATE_ERR_RECORDS}

// Processing form data when form is submitted
if(isset($_POST["{COLUMN_ID}"]) && !empty($_POST["{COLUMN_ID}"])){
    // Get hidden input value
    ${COLUMN_ID} = $_POST["{COLUMN_ID}"];

    {CREATE_POST_VARIABLES}

    // Prepare an update statement
    $dsn = "mysql:host=$db_server;dbname=$db_name;charset=utf8mb4";
    $options = [
        PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
    ];
    try {
        $pdo = new PDO($dsn, $db_user, $db_password, $options);
    } catch (Exception $e) {
        error_log($e->getMessage());
        exit('Something weird happened');
    }

    $vars = parse_columns('{TABLE_NAME}', $_POST);
    $stmt = $pdo->prepare("UPDATE {TABLE_NAME} SET {UPDATE_SQL_PARAMS} WHERE {UPDATE_SQL_ID}");

    if(!$stmt->execute([ {UPDATE_SQL_COLUMNS}  ])) {
        echo "Something went wrong. Please try again later.";
        header("location: error.php");
    } else {
        $stmt = null;
        header("location: {TABLE_NAME}-read.php?{COLUMN_ID}=${COLUMN_ID}");
    }
} else {
    // Check existence of id parameter before processing further
	$_GET["{COLUMN_ID}"] = trim($_GET["{COLUMN_ID}"]);
    if(isset($_GET["{COLUMN_ID}"]) && !empty($_GET["{COLUMN_ID}"])){
        // Get URL parameter
        ${COLUMN_ID} =  trim($_GET["{COLUMN_ID}"]);

        // Prepare a select statement
        $sql = "SELECT * FROM {TABLE_NAME} WHERE {COLUMN_ID} = ?";
        if($stmt = mysqli_prepare($link, $sql)){
            // Set parameters
            $param_id = ${COLUMN_ID};

            // Bind variables to the prepared statement as parameters
			if (is_int($param_id)) $__vartype = "i";
			elseif (is_string($param_id)) $__vartype = "s";
			elseif (is_numeric($param_id)) $__vartype = "d";
			else $__vartype = "b"; // blob
			mysqli_stmt_bind_param($stmt, $__vartype, $param_id);

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                $result = mysqli_stmt_get_result($stmt);

                if(mysqli_num_rows($result) == 1){
                    /* Fetch result row as an associative array. Since the result set
                    contains only one row, we don't need to use while loop */
                    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

                    // Retrieve individual field value

                    {UPDATE_COLUMN_ROWS}

                } else{
                    // URL doesn't contain valid id. Redirect to error page
                    header("location: error.php");
                    exit();
                }

            } else{
                echo "Oops! Something went wrong. Please try again later.<br>".$stmt->error;
            }
        }

        // Close statement
        mysqli_stmt_close($stmt);

    }  else{
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<?php require_once('navbar.php'); ?>
<body>
    <section class="pt-5">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6 mx-auto border border-danger">
                    <div class="page-header">
                        <h2>Update Database Record</h2>
                    </div>
                    <p>Please edit the input values and submit to update the record.</p>
                    <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">

                        {CREATE_HTML}

                        <input type="hidden" name="{COLUMN_ID}" value="<?php echo ${COLUMN_ID}; ?>"/>
                        <input type="submit" class="btn btn-primary" value="Submit">
                        <a href="{TABLE_NAME}-index.php" class="btn btn-secondary">Cancel</a>
                    </form>
                </div>
            </div>
        </div>
    </section>
</body>
</html>

EOT;

$errorfile = <<<'EOT'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Error</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
    <section class="pt-5">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="page-header">
                        <h1>Invalid Request</h1>
                    </div>
                    <div class="alert alert-danger fade-in">
                        <p>Sorry, you've made an invalid request. Please <a href="index.php" class="alert-link">go back</a> and try again.</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
EOT;

$startfile = <<<'EOT'
<?php
if ($_SERVER["SERVER_PORT"]!=443){ header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); exit(); }
?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{APP_NAME}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <style type="text/css">
        .page-header h2{
            margin-top: 0;
        }
        table tr td:last-child a{
            margin-right: 5px;
        }
    </style>
</head>
<?php require_once('navbar.php'); ?>
</html>  
EOT;

$navbarfile = <<<'EOT'
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand nav-link disabled" href="#"><?=$appname?></a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Select Page
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        {TABLE_BUTTONS}
     <?php if(isset($_SESSION['user_session'])) { ?>
        <a href="logout.php" class="dropdown-item">Logout</a>
     <?php } ?>
        <!-- TABLE_BUTTONS -->
        </div>
      </li>
    </ul>
  </div>
</nav>
EOT;

$export2excel = <<<'EOT'
<?php 

// Load the database configuration file 
include_once 'config.php'; 
include_once 'helpers.php';

// Filter the excel data 
function filterData(&$str){ 
    $str = preg_replace("/\t/", "\\t", $str); 
    $str = preg_replace("/,/", " ", $str); 
    $str = preg_replace("/\r?\n/", "\\n", $str); 
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; 
} 
 
// Excel file name for download 
$fileName = {TABLE_NAME}."_".date('Y-m-d') . ".xlsx";

$sql = "SHOW COLUMNS FROM {TABLE_NAME}";
           if($output = mysqli_query($link,$sql)):
                $fields = array();
                while($result = mysqli_fetch_assoc($output)):
                    $fields[] = $result['Field'];
                endwhile;
            endif;
 
// Display column names as first row 
$excelData = implode("\t", array_values($fields)) . "\n"; 
 
// Fetch records from database 
$query = "SELECT * FROM {TABLE_NAME}";
$response = mysqli_query($link, $query);
if(mysqli_num_rows($response) > 0){ 
  // Output each row of the data 
    $lineData = [];
      while ($lineData = mysqli_fetch_array($response,MYSQLI_ASSOC)) {
         array_walk($lineData, 'filterData'); 
         $excelData .= implode("\t", array_values($lineData)) . "\n"; 
   }
 } else { 
    $excelData .= 'No records found...'. "\n"; 
 } 
 
// Headers for download 
  header("Content-Type: application/vnd.ms-excel"); 
  header("Content-Disposition: attachment; filename=\"$fileName\""); 
 
// Render excel data 
  echo $excelData; 
 
  exit;

?>
EOT;

/* NEW TEMPLATE ADDITIONS HERE */

$userauth = <<<'EOT'
<?php

// Change these to suit your situation after Cruddiy generates the scripts

        $realm = "{APP_NAME}";
        $username = "test";
        $passwd = "123456";

/* NOTHING TO CHANGE BEYOND THIS POINT */

  $PHP_AUTH_USER = $_SERVER['PHP_AUTH_USER'];
  $PHP_AUTH_PW = $_SERVER['PHP_AUTH_PW'];


$err_msg = "
	<html>
	<head><title>Invalid Username/Password Entered</title>
	</head>
	<body style='font-size: 11px\; font-family: Tahoma, Arial, sans-serif\;'>
	<h2>Invalid Username/Password Entered</h2>
	<p>You must enter your username and password. If you do not have a valid username and password, you should not be here.</p>
	</body>
	</html>
	";

function auth_reject()
	{
		global $err_msg, $realm;
		header('WWW-Authenticate: Basic realm=\"{APP_NAME}\"');
		header('HTTP/1.0 401 Unauthorized');
		echo "<b>" . $err_msg . "</b>";
		exit;
	}
	
	if (!isset($PHP_AUTH_USER))
		{
		auth_reject();
		}
	
	if (!isset($PHP_AUTH_PW))
	{
		auth_reject();
	}
	
	if ($PHP_AUTH_USER != $username)
	{
		auth_reject();
	}
	
	if ($PHP_AUTH_PW != $passwd)
	{
		auth_reject();
	}

?>
EOT;

$stylesheet = <<<'EOT'
@charset "utf-8";

body {
        padding-bottom: 40px;
        background-color: #f7f7f7;
      }
.container
{
 margin-top:80px;
}
h2
{
 font-family:Tahoma, Geneva, sans-serif;
 color:#00a2d1;
}
.form-container
{
 width:500px;
 margin:0 auto;
 background:#fff;
 padding: 25px;
 box-shadow: 0px 0px 2px rgba(0,0,0,0.4);
 border-radius:3px;
}
button
{
 font-family:Verdana, Geneva, sans-serif;
 font-size:25px;
}
label
{
 font-family:Tahoma, Geneva, sans-serif;
 color:.00a9d1;
}
a
{
 text-decoration:underline;
}

/* home page style */

.header
{
 text-align:center;
 font-size:25px;
 color:#fff;
 background:#00a2d1;
 height:60px;
 width:100%;
}
.header a
{
 color:#f9f9f9;
 font-family:Verdana, Geneva, sans-serif;
 font-size:25px;
 text-decoration:none;
 position:relative;
 top:15px;
}
.header .left
{
 float:left;
 position:relative;
 left:150px;
}
.header .right
{
 float:right;
 position:relative;
 right:150px;
}
.content
{
 margin:0 auto;
 margin-top:50px;
 text-align:center;
 font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
 font-size:36px;
 color:#00a2d1;
}
.content p
{
 font-size:24px;
 color:#004567;
 width:800px;
 margin:0 auto;
} 
EOT;

$login = <<<'EOT'
<?php
@session_start();
require_once 'config.php';

if($user->is_loggedin()!="")
{
 $user->redirect('{TABLE_NAME}-index.php');
}

if(isset($_POST['btn-login']))
{
 $uname = $_POST['txt_uname_email'];
 $umail = $_POST['txt_uname_email'];
 $upass = $_POST['txt_password'];
  
 if($user->login($uname,$umail,$upass))
 {
  $user->redirect('{TABLE_NAME}-index.php');
 }
 else
 {
  $error = "Oops! Something's Not Right. Please Try Again . . .";
 } 
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?=$appname?> Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css" type="text/css"  />

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

</head>
<body>
<div class="container">
     <div class="form-container">
        <form method="post">
            <h2><?=$appname?> Sign In</h2><hr />
            <?php
            if(isset($error))
            {
                  ?>
                  <div class="alert alert-danger">
                      <i class="glyphicon glyphicon-warning-sign"></i> &nbsp; <?php echo $error; ?>
                  </div>
                  <?php
            }
            ?>
            <div class="form-group">
             <input type="text" class="form-control" name="txt_uname_email" placeholder="Username or Email Address" required />
            </div>
            <div class="form-group">
             <input type="password" class="form-control" name="txt_password" placeholder="Your Password" required />
            </div>
            <div class="clearfix"></div><hr />
            <div class="form-group">
             <button type="submit" name="btn-login" class="btn btn-block btn-primary">
                 <i class="glyphicon glyphicon-log-in"></i>&nbsp;SIGN IN
                </button>
            </div>
            <br />
	<div class="float-right">
            <label><a href="sign-up.php" class="text-decoration-none"><b>~</b></a></label>
	</div>
        </form>
       </div>
</div>

</body>
</html>
EOT;

$logout = <<<'EOT'
<?php
@session_start();
session_destroy();
  
header('location:index.php');
  
?>
EOT;

$signup = <<<'EOT'
<?php
@session_start();

require_once 'config.php';

if($user->is_loggedin()!="")
{
    $user->redirect('{TABLE_NAME}-index.php');
}

if(isset($_POST['btn-signup']))
{
   $uname = trim($_POST['txt_uname']);
   $umail = trim($_POST['txt_umail']);
   $upass = trim($_POST['txt_upass']); 
 
   if($uname=="") {
      $error[] = "Please enter a username !"; 
   }
   else if($umail=="") {
      $error[] = "Please enter an email address !"; 
   }
   else if(!filter_var($umail, FILTER_VALIDATE_EMAIL)) {
      $error[] = 'Please enter a valid email address !';
   }
   else if($upass=="") {
      $error[] = "Please enter a password !";
   }
   else if(strlen($upass) < 6){
      $error[] = "Your password must be at least 6 characters long"; 
   }
   else
   {
      try
      {
         $stmt = $DB_con->prepare("SELECT user_name,user_email FROM users_table WHERE user_name=:uname OR user_email=:umail");
         $stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
         $row=$stmt->fetch(PDO::FETCH_ASSOC);
    
         if($row['user_name']==$uname) {
            $error[] = "Sorry . . . that username is already taken!";
         }
         else if($row['user_email']==$umail) {
            $error[] = "Sorry . . . that email address is already taken!";
         }
         else
         {
            if($user->register($fname,$lname,$uname,$umail,$upass)) 
            {
                $user->redirect('sign-up.php?joined');
            }
         }
     }
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }
  } 
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?=$appname?> Sign Up</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css" type="text/css"  />
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

</head>
<body>
<div class="container">
     <div class="form-container">
        <form method="post">
            <h2><?=$appname?> Sign Up</h2><hr />
            <?php
            if(isset($error))
            {
               foreach($error as $error)
               {
                  ?>
                  <div class="alert alert-danger">
                      <i class="glyphicon glyphicon-warning-sign"></i> &nbsp; <?php echo $error; ?>
                  </div>
                  <?php
               }
            }
            else if(isset($_GET['joined']))
            {
                 ?>
                 <div class="alert alert-info">
                      <i class="glyphicon glyphicon-log-in"></i> &nbsp; Successfully registered <a href='index.php'>login</a> here
                 </div>
                 <?php
            }
            ?>
            <div class="form-group">
            <input type="text" class="form-control" name="txt_uname" placeholder="Enter Username" value="<?php if(isset($error)){echo $uname;}?>" />
            </div>
            <div class="form-group">
            <input type="text" class="form-control" name="txt_umail" placeholder="Enter E-Mail Address" value="<?php if(isset($error)){echo $umail;}?>" />
            </div>
            <div class="form-group">
             <input type="password" class="form-control" name="txt_upass" placeholder="Enter Password" />
            </div>
            <div class="clearfix"></div><hr />
            <div class="form-group">
             <button type="submit" class="btn btn-block btn-primary" name="btn-signup">
                 <i class="glyphicon glyphicon-open-file"></i>&nbsp;SIGN UP
                </button>
            </div>
            <br />
            <label>Already have an account? <a href="login.php">Sign In</a></label>
        </form>
       </div>
</div>

</body>
</html>
EOT;