Handling Dynamic Data Fields using Database Vertical Table Design in PHP Tutorial
In this tutorial, we will tackle Handing Dynamic Data Fileds using Database Vertical Table Design. This idea is very useful for such web applications that handling multiple data. This will prevent multiple columns in your database table. Also, this will help you to store new data fields without making changes in your database table structure.
This tutorial can also help you learn some techniques or ideas for developing a web application. The simple web application that we will make for this tutorial contains a dynamic modal, dynamic confirmation modal, and flash message. The said features can lessen/prevent redundancy when writing your codes.
Getting Started
In this tutorial, we will be using XAMPP as our local web server tp run our PHP Scripts and for our MySQL Database Server.
Also, download and install the following:
Compile all the download libraries in a directory inside your XAMPP's 'htdocs' directory. Then, open your XAMPP's Control Panel and start the Apache and MySQL.
Creating Our Database
Open your PHPMyAdmin i.e. http://localhost/phpmyadmin
and create a new database naming dummy_db. Then, navigate to the SQL Tab and copy/paste
the mysql script below.
- ('Contact #', 'contact_number', 'Numeric'),
- ('Address', 'address', 'Long Text'),
- ('Sample Details', 'sample_detail1', 'Long Text');
- (1, '6231415', 'John', 'D', 'Smith', '2021-10-09 13:43:38', '2021-10-09 13:46:35');
- (1, 'contact_number', '09123456798'),
- (1, 'address', 'Sample Address'),
- (1, 'sample_detail1', 'Sample Data only');
- ADD CONSTRAINT `student_meta_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `student_list` (`id`) ON DELETE CASCADE;
Creating Our Database Connection
Open a your text editor software such as (sublime, notepad++, or vs code). Create a new PHP file naming connection.php. Then, copy/paste
the script below.
- <?php
- $host = "localhost";
- $username = "root";
- $password = "";
- $db_tbl = "dummy_db";
- $conn=new mysqli($host,$username,$password,$db_tbl);
- if(!$conn){
- }
Creating the custom Javascript File
The code below is the script which contains the javascript/jquery functions for our dynamic modal and confirmation modal. Save this file as script.js. In my case, this file is located inside the js folder where all the javascript file of the libraries are compiled.
- window.uni_modal = function($title = '', $url = '', $size = "") {
- $.ajax({
- url: $url,
- error: err => {
- console.log()
- alert("An error occured")
- },
- success: function(resp) {
- if (resp) {
- $('#uni_modal .modal-title').html($title)
- $('#uni_modal .modal-body').html(resp)
- $('#uni_modal .modal-dialog').removeClass('large')
- $('#uni_modal .modal-dialog').removeClass('mid-large')
- $('#uni_modal .modal-dialog').removeClass('modal-md')
- if ($size == '') {
- $('#uni_modal .modal-dialog').addClass('modal-md')
- } else {
- $('#uni_modal .modal-dialog').addClass($size)
- }
- $('#uni_modal').modal({
- backdrop: 'static',
- keyboard: true,
- focus: true
- })
- $('#uni_modal').modal('show')
- }
- }
- })
- }
- window._conf = function($msg = '', $func = '', $params = []) {
- $('#confirm_modal #confirm').attr('onclick', $func + "(" + $params.join(',') + ")")
- $('#confirm_modal .modal-body').html($msg)
- $('#confirm_modal').modal('show')
- }
Creating the Interfaces
The PHP File scripts below are the codes for the pages in our simple web application. Save the files according the filename above each scripts.
index.phpThis is the file for our web application template. This contains the html scripts for our web application document.
- <?php
- require_once('connection.php');
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Dynamic Data</title>
- <link rel="stylesheet" href="./css/bootstrap.min.css">
- <script src="./js/jquery-3.6.0.min.js"></script>
- <script src="./js/popper.min.js"></script>
- <script src="./js/bootstrap.min.js"></script>
- <script src="./js/script.js"></script>
- <style>
- .modal-dialog.large {
- width: 80% !important;
- max-width: unset;
- }
- .modal-dialog.mid-large {
- width: 50% !important;
- max-width: unset;
- }
- @media (max-width:720px){
- .modal-dialog.large {
- width: 100% !important;
- max-width: unset;
- }
- .modal-dialog.mid-large {
- width: 100% !important;
- max-width: unset;
- }
- }
- </style>
- </head>
- <body class="bg-light">
- <main>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient" id="topNavBar">
- <div class="container">
- <a class="navbar-brand" href="./">
- Sourcecodester
- </a>
- <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
- <div class="collapse navbar-collapse" id="navbarNav">
- <ul class="navbar-nav">
- <li class="nav-item">
- <a class="nav-link <?php echo ($page == 'student')? 'active' : '' ?>" aria-current="page" href="./"><i class="fa fa-user-friends"></i> Student List</a>
- </li>
- <li class="nav-item">
- <a class="nav-link <?php echo ($page == 'settings')? 'active' : '' ?>" aria-current="page" href="./?page=settings"><i class="fa fa-cogs"></i> Settings</a>
- </li>
- </ul>
- </div>
- </div>
- </nav>
- <div class="container py-5 mb-4">
- <h3>Dynamic Data using Vertical Database Table Design</h3>
- <hr>
- <?php
- ?>
- <div class="alert alert-<?php echo $_SESSION['flashdata']['type'] ?>">
- <div class="w-100 d-flex">
- <p class="col-auto flex-grow-1 m-0"><?php echo $_SESSION['flashdata']['msg'] ?></p>
- <div class="col-auto">
- <button class="btn-close" onclick="$(this).closest('.alert').remove()"></button>
- </div>
- </div>
- </div>
- <?php
- endif;
- ?>
- <?php include($page.'.php') ?>
- </div>
- </main>
- <!-- Universal Modal -->
- <div class="modal fade" id="uni_modal" role='dialog' data-bs-backdrop="static" data-bs-keyboard="true">
- <div class="modal-dialog modal-md modal-dialog-centered" role="document">
- <div class="modal-content">
- <div class="modal-header py-2">
- <h5 class="modal-title"></h5>
- </div>
- <div class="modal-body pb-0 mb-0">
- </div>
- </div>
- </div>
- </div>
- <!-- Universal Modal End -->
- <!-- Confirmation Modal End -->
- <div class="modal fade" id="confirm_modal" role='dialog'>
- <div class="modal-dialog modal-md modal-dialog-centered" role="document">
- <div class="modal-content rounded-0">
- <div class="modal-header py-2">
- <h5 class="modal-title">Confirmation</h5>
- </div>
- <div class="modal-body">
- <div id="delete_content"></div>
- </div>
- <div class="modal-footer py-1">
- <button type="button" class="btn btn-primary btn-sm rounded-0" id='confirm' onclick="">Continue</button>
- <button type="button" class="btn btn-secondary btn-sm rounded-0" data-bs-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- <!-- Confirmation Modal End -->
- </body>
- </html>
This file contains the PHP and HTML scripts of the students list page.
- <div class="col-md-12" id="">
- <div class="w-100 my-2 d-flex">
- <h4 class="col-auto flex-grow-1"><b>Student List</b></h4>
- <div class="col-auto">
- <a href="./?page=manage_student" class="btn btn-sm btn-primary rounded-0">Add New</a>
- </div>
- </div>
- <hr>
- <div class="col-12">
- <table class="table table-striped table-hover">
- <thead>
- <tr class="bg-dark text-light">
- <th class="py-1 px-2">#</th>
- <th class="py-1 px-2">Date Created</th>
- <th class="py-1 px-2">Stundet Code</th>
- <th class="py-1 px-2">Student Name</th>
- <th class="py-1 px-2">Date Updated</th>
- <th class="py-1 px-2">Action</th>
- </tr>
- </thead>
- <tbody>
- <?php
- $i = 1;
- $students = $conn->query("SELECT *,CONCAT(lastname, ', ', firstname, ' ', middlename) as fullname FROM `student_list` order by fullname asc ");
- while($row= $students->fetch_assoc()):
- ?>
- <tr>
- <td class="py-1 px-2 text-center"><?php echo $i++ ?></td>
- <td class="py-1 px-2"><?php echo $row['student_code'] ?></td>
- <td class="py-1 px-2">
- <div class="dropstart">
- <button class="btn btn-primary btn-sm rounded-0 dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
- Action
- </button>
- <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
- <li><a class="dropdown-item view_data" href="javascript:void(0)" data-id="<?php echo $row['id'] ?>">View</a></li>
- <li><a class="dropdown-item" href=".?page=manage_student&id=<?php echo $row['id'] ?>">Edit</a></li>
- <li><a class="dropdown-item delete_data" href="javascript:void(0)" data-id="<?php echo $row['id'] ?>" data-name="<?php echo $row['student_code']." - ".$row['fullname'] ?>">Delete</a></li>
- </ul>
- </div>
- </td>
- </tr>
- <?php endwhile; ?>
- <?php if($students->num_rows <= 0): ?>
- <tr>
- <th class="py-1 px-2 text-center" colspan='6'>No Data to Display</th>
- </tr>
- <?php endif; ?>
- </tbody>
- </table>
- </div>
- </div>
- <script>
- $(function(){
- // View Student Details Form Modal
- $('.view_data').click(function(){
- uni_modal('Student Details','view_data.php?id='+$(this).attr('data-id'),"large")
- })
- // Delete Student Form Modal
- $('.delete_data').click(function(){
- _conf("Are you sure to delete <b>"+$(this).attr('data-name')+"</b>?", "delete_data",["'"+$(this).attr('data-id')+"'"]);
- })
- })
- function delete_data($id){
- $('#confirm_modal button').attr('disabled',true)
- $.ajax({
- url:'api.php?action=delete_student',
- method:'POST',
- data:{id:$id},
- dataType:'JSON',
- error:err=>{
- console.log(err)
- alert("An error occurred.")
- $('#confirm_modal button').attr('disabled',false)
- },
- success:function(resp){
- if(resp.status == 'success'){
- location.reload()
- }else{
- alert("An error occurred.")
- $('#confirm_modal button').attr('disabled',false)
- }
- }
- })
- }
- </script>
This file contains the codes/script for the student form.
- <?php
- require_once('connection.php');
- $qry= $conn->query("SELECT * FROM student_list where id = '{$_GET['id']}' ");
- foreach($qry->fetch_array() as $k => $v){
- $$k = $v;
- }
- $qry2 = $conn->query("SELECT * from student_meta where student_id = '{$id}'");
- while($row = $qry2->fetch_assoc()){
- $meta[$row['meta_field']] = $row['meta_value'];
- }
- }
- }
- $mdata = $conn->query("SELECT * FROM data_meta ");
- while($row = $mdata->fetch_assoc()){
- $fields[] = $row;
- }
- ?>
- <div class="container-fluid">
- <form action="" id="student-form">
- <div class="col-md-12">
- <div class="row gy-2 gx-5 row-cols-1 row-cols-sm-1 row-cols-xl-2 row-cols-md-2">
- <div class="col">
- <div class="form-group">
- <label for="student_code" class="control-label">Student Code</label>
- <input type="text" id="student_code" name="student_code" class="form-control form-control-sm rounded-0" value="<?php echo isset($student_code) ? $student_code : '' ?>" required>
- </div>
- </div>
- <div class="col"></div>
- <div class="col">
- <div class="form-group">
- <label for="firstname" class="control-label">First Name</label>
- <input type="text" id="firstname" name="firstname" class="form-control form-control-sm rounded-0" value="<?php echo isset($firstname) ? $firstname : '' ?>" required>
- </div>
- </div>
- <div class="col">
- <div class="form-group">
- <label for="middlename" class="control-label">Middle Name</label>
- <input type="text" id="middlename" name="middlename" class="form-control form-control-sm rounded-0" value="<?php echo isset($middlename) ? $middlename : '' ?>" placeholder="optional">
- </div>
- </div>
- <div class="col">
- <div class="form-group">
- <label for="lastname" class="control-label">Last Name</label>
- <input type="text" id="lastname" name="lastname" class="form-control form-control-sm rounded-0" value="<?php echo isset($lastname) ? $lastname : '' ?>" required>
- </div>
- </div>
- <?php foreach($fields as $field): ?>
- <div class="col">
- <div class="form-group">
- <label for="<?php echo $field['meta_field_name'] ?>" class="control-label"><?php echo $field['meta_label'] ?></label>
- <?php if($field['type'] == 'Text'): ?>
- <input type="text" id="<?php echo $field['meta_field_name'] ?>" name="<?php echo $field['meta_field_name'] ?>" class="form-control form-control-sm rounded-0" value="<?php echo isset($meta[$field['meta_field_name']]) ? $meta[$field['meta_field_name']] : '' ?>" required>
- <?php elseif($field['type'] == 'Numeric'): ?>
- <input type="number" id="<?php echo $field['meta_field_name'] ?>" name="<?php echo $field['meta_field_name'] ?>" class="form-control form-control-sm rounded-0" value="<?php echo isset($meta[$field['meta_field_name']]) ? $meta[$field['meta_field_name']] : '' ?>" required>
- <?php else: ?>
- <textarea rows="3" id="<?php echo $field['meta_field_name'] ?>" name="<?php echo $field['meta_field_name'] ?>" style="resize:none" class="form-control form-control-sm rounded-0"><?php echo isset($meta[$field['meta_field_name']]) ? $meta[$field['meta_field_name']] : '' ?></textarea>
- <?php endif; ?>
- </div>
- </div>
- <?php endforeach; ?>
- <?php endif; ?>
- </div>
- </div>
- <div class="col-12 py-2">
- <div class="w-100 d-flex justify-content-center">
- <button class="btn btn-sm btn-primary rounded-0 me-2">Save</button>
- <a href="./?page=student" class="btn btn-sm btn-dark rounded-0">Back</a>
- </div>
- </div>
- </form>
- </div>
- <script>
- $(function(){
- $('#student-form').submit(function(e){
- e.preventDefault()
- var _this = $(this)
- _this.find('button').attr('disabled',true)
- $('.pop_msg').remove()
- $.ajax({
- url:'api.php?action=save_student',
- method:'POST',
- data:_this.serialize(),
- dataType:'json',
- error:err=>{
- console.log(err)
- alert('an error occured')
- _this.find('button').attr('disabled',false)
- },
- success:function(resp){
- if(resp.status == 'success'){
- location.replace('./')
- }else if(resp.status == 'failed' && !!resp.msg){
- var el = $('<div>')
- el.addClass('pop_msg alert alert-danger')
- .css('display','none')
- .text(resp.msg)
- _this.prepend(el)
- el.show('slow')
- }else{
- console.log(resp)
- alert('an error occured')
- }
- _this.find('button').attr('disabled',false)
- }
- })
- })
- })
- </script>
This file contains the script of the student data modal.
- <?php
- require_once('connection.php');
- $qry= $conn->query("SELECT *,CONCAT(lastname, ', ', firstname, ' ', middlename) as fullname FROM student_list where id = '{$_GET['id']}' ");
- foreach($qry->fetch_array() as $k => $v){
- $$k = $v;
- }
- $qry2 = $conn->query("SELECT * from student_meta where student_id = '{$id}'");
- while($row = $qry2->fetch_assoc()){
- $meta[$row['meta_field']] = $row['meta_value'];
- }
- }
- }
- $mdata = $conn->query("SELECT * FROM data_meta ");
- while($row = $mdata->fetch_assoc()){
- $fields[] = $row;
- }
- ?>
- <div class="container-fuid">
- <div class="col-12">
- <div class="row gy-2 gx-5 row-cols-1 row-cols-sm-1 row-cols-xl-2 row-cols-md-2">
- <div class="col">
- <div class="text-muted">Student Code:</div>
- <div class="lh-1 fs-6"><?php echo $student_code ?></div>
- </div>
- <div class="col">
- <div class="text-muted">Student Name:</div>
- </div>
- <div class="col">
- <div class="text-muted">Student Code:</div>
- <div class="lh-1 fs-6"><?php echo $student_code ?></div>
- </div>
- <?php foreach($fields as $field): ?>
- <div class="col">
- <div class="text-muted"><?php echo $field['meta_label'] ?>:</div>
- <p class="lh-1 fs-6"><?php echo isset($meta[$field['meta_field_name']]) ? $meta[$field['meta_field_name']] : '' ?></p>
- </div>
- <?php endforeach; ?>
- <?php endif; ?>
- </div>
- </div>
- </div>
- <div class="row justify-content-end mx-0 my-2">
- <div class="col-auto">
- <button class="btn btn-sm btn-dark rounded-0" data-bs-dismiss="modal">Close</button>
- </div>
- </div>
This file contains the list of dynamic data fields in our database table.
- <div class="col-lg-12">
- <div class="w-100 my-2 d-flex">
- <h4 class="col-auto flex-grow-1"><b>Dynamic Data Fields</b></h4>
- <div class="col-auto">
- <a href="javascript:void(0)" id="add_new" class="btn btn-sm btn-primary rounded-0">Add New</a>
- </div>
- </div>
- <table class="table table-striped table-hover">
- <thead>
- <tr class="bg-dark text-light">
- <th class="py-1 px-2">#</th>
- <th class="py-1 px-2">Field Label</th>
- <th class="py-1 px-2">Field Name</th>
- <th class="py-1 px-2">Type</th>
- <th class="py-1 px-2">Action</th>
- </tr>
- </thead>
- <tbody>
- <?php
- $i = 1;
- $students = $conn->query("SELECT * FROM `data_meta` ");
- while($row= $students->fetch_assoc()):
- ?>
- <tr>
- <td class="py-1 px-2 text-center"><?php echo $i++ ?></td>
- <td class="py-1 px-2"><?php echo $row['meta_label'] ?></td>
- <td class="py-1 px-2"><?php echo $row['meta_field_name'] ?></td>
- <td class="py-1 px-2"><?php echo $row['type'] ?></td>
- <td class="py-1 px-2">
- <div class="dropdown">
- <button class="btn btn-primary btn-sm rounded-0 dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
- Action
- </button>
- <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
- <li><a class="dropdown-item edit_data" href="javascript:void(0)" data-meta_field_name="<?php echo $row['meta_field_name'] ?>">Edit</a></li>
- <li><a class="dropdown-item delete_data" href="javascript:void(0)" data-meta_field_name="<?php echo $row['meta_field_name'] ?>">Delete</a></li>
- </ul>
- </div>
- </td>
- </tr>
- <?php endwhile; ?>
- <?php if($students->num_rows <= 0): ?>
- <tr>
- <th class="py-1 px-2 text-center" colspan='5'>No Data to Display</th>
- </tr>
- <?php endif; ?>
- </tbody>
- </table>
- </div>
- <script>
- $(function(){
- // Add New Data Form Modal
- $('#add_new').click(function(){
- uni_modal("Add New Data Field", "manage_field.php");
- })
- // Edit Data Form Modal
- $('.edit_data').click(function(){
- uni_modal("Edit Data Field", "manage_field.php?meta_field_name="+$(this).attr('data-meta_field_name'));
- })
- // Delete Data Form Modal
- $('.delete_data').click(function(){
- _conf("Are you sure to delete <b>"+$(this).attr('data-meta_field_name')+"</b>?", "delete_data",["'"+$(this).attr('data-meta_field_name')+"'"]);
- })
- })
- function delete_data($meta_field_name){
- $('#confirm_modal button').attr('disabled',true)
- $.ajax({
- url:'api.php?action=delete_field',
- method:'POST',
- data:{meta_field_name:$meta_field_name},
- dataType:'JSON',
- error:err=>{
- consolre.log(err)
- alert("An error occurred.")
- $('#confirm_modal button').attr('disabled',false)
- },
- success:function(resp){
- if(resp.status == 'success'){
- location.reload()
- }else{
- alert("An error occurred.")
- $('#confirm_modal button').attr('disabled',false)
- }
- }
- })
- }
- </script>
This file is the script for the dynamic data field form modal.
- <?php
- require_once('connection.php');
- $qry= $conn->query("SELECT * FROM data_meta where meta_field_name = '{$_GET['meta_field_name']}' ");
- foreach($qry->fetch_array() as $k => $v){
- $$k = $v;
- }
- }
- ?>
- <div class="container-fluid">
- <form action="" id="field-form">
- <input type="hidden" name="o_field_name" value="<?php echo isset($meta_field_name)? $meta_field_name : "" ?>">
- <div class="form-group">
- <label for="meta_label" class="control-label">Label</label>
- <input type="text" id="meta_label" name="meta_label" class="form-control form-control-sm rounded-0" value="<?php echo isset($meta_label) ? $meta_label : '' ?>" required>
- </div>
- <div class="form-group">
- <label for="meta_field_name" class="control-label">Field Name</label>
- <input type="text" id="meta_field_name" name="meta_field_name" class="form-control form-control-sm rounded-0" pattern="[a-z0-9A-Z_]+" value="<?php echo isset($meta_field_name) ? $meta_field_name : '' ?>" required>
- <small class="text-info">(Accepted Characters: A-Z, a-z, '_' )</small>
- </div>
- <div class="form-group">
- <label for="type" class="control-label">Field Type</label>
- <select name="type" id="type" class="form-select form-select-sm rounded">
- </select>
- </div>
- </form>
- </div>
- <div class="row justify-content-end mx-0 my-2">
- <div class="col-auto">
- <button class="btn btn-sm btn-primary rounded-0 me-2" form="field-form">Save</button>
- <button class="btn btn-sm btn-dark rounded-0" data-bs-dismiss="modal">Close</button>
- </div>
- </div>
- <script>
- $(function(){
- $('#field-form').submit(function(e){
- e.preventDefault()
- var _this = $(this)
- _this.find('button').attr('disabled',true)
- $('.pop_msg').remove()
- $.ajax({
- url:'api.php?action=save_field',
- method:'POST',
- data:_this.serialize(),
- dataType:'json',
- error:err=>{
- console.log(err)
- alert('an error occured')
- _this.find('button').attr('disabled',false)
- },
- success:function(resp){
- if(resp.status == 'success'){
- location.reload()
- }else if(resp.status == 'failed' && !!resp.msg){
- var el = $('<div>')
- el.addClass('pop_msg alert alert-danger')
- .css('display','none')
- .text(resp.msg)
- _this.prepend(el)
- el.show('slow')
- }else{
- console.log(resp)
- alert('an error occured')
- }
- _this.find('button').attr('disabled',false)
- }
- })
- })
- })
- </script>
Creating our PHP API
The script below is the file that contains our PHP API which queries (Insert, Update, and Delete) data in our database. Save this PHP File as api.php.
- <?php
- require_once('connection.php');
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- // Extracting Post data to varialbles
- }
- $resp['status'] ='failed';
- $resp['msg'] = 'Unknown Action';
- }
- elseif($action == 'save_field'){
- $data = "";
- $check = $conn->query("SELECT * FROM `data_meta` where meta_field_name = '{$meta_field_name}' ".(!empty($o_field_name)? " and meta_field_name != '{$o_field_name}'" : '' ))->num_rows;
- if($check > 0){
- $resp['status'] ='failed';
- $resp['msg'] ='Field Name Already Exists.';
- }else{
- $sql = "INSERT INTO `data_meta` (meta_label,meta_field_name,`type`) VALUES ('{$meta_label}','{$meta_field_name}','{$type}')";
- }else{
- $sql = "UPDATE `data_meta` set `meta_label` = '{$meta_label}', `meta_field_name` = '{$meta_field_name}', `type` = '{$type}' where `meta_field_name` = '{$o_field_name}'";
- $sql2 = "UPDATE `student_meta` set `meta_field` = '{$meta_field_name}' where `meta_field` = '{$o_field_name}'";
- }
- $save = $conn->query($sql);
- $conn->query($sql2);
- if($save){
- $resp['status'] = 'success';
- $_SESSION['flashdata']['type'] = 'success';
- $_SESSION['flashdata']['msg'] = 'Field Successfuly Saved';
- }else{
- $resp['status'] = 'failed';
- $resp['msg'] = 'Failed to saved data. Error: '.$conn->error;
- }
- }
- }
- elseif($action == 'delete_field'){
- $delete = $conn->query("DELETE FROM `data_meta` where meta_field_name = '{$meta_field_name}'");
- if($delete){
- $resp['status'] = 'success';
- $_SESSION['flashdata']['type'] = 'success';
- $_SESSION['flashdata']['msg'] = 'Data Field successfully deleted.';
- }else{
- $resp['status'] = 'failed';
- $resp['msg'] = 'Error: '.$conn->error;
- }
- }
- elseif($action == 'save_student'){
- // static data
- $data = "";
- $check = $conn->query("SELECT * FROM `student_list` where student_code = '{$student_code}' ".(!empty($id)? " and id != '{$id}'" : '' ))->num_rows;
- if($check > 0){
- $resp['status'] ='failed';
- $resp['msg'] ='Student Code Already Exists.';
- }else{
- // dynamically set data to insert or update
- foreach($_POST as $k =>$v){
- continue;
- $v= $conn->real_escape_string($v);
- $data .= " `$k` = '{$v}' ";
- }
- $sql = "INSERT INTO `student_list` set {$data}";
- }else{
- $sql = "UPDATE `student_list` set {$data} where id = '{$id}'";
- }
- $save = $conn->query($sql);
- if($save){
- $data = "";
- $resp['status'] ='success';
- $_SESSION['flashdata']['type'] = 'success';
- $_SESSION['flashdata']['msg'] = 'Student Data Successfuly Saved';
- // setting the dynamic data for insertion
- foreach($_POST as $k =>$v){
- continue;
- $v= $conn->real_escape_string($v);
- $data .= " ('{$student_id}','{$k}', '{$v}' )";
- }
- // Deleting the old dynamic data
- $conn->query("DELETE FROM student_meta where student_id = '{$student_id}'");
- // Inserting Updated dynamic Data
- $conn->query("INSERT INTO student_meta (`student_id`,`meta_field`,`meta_value`) VALUES {$data} ");
- }
- }else{
- $resp['status'] = 'failed';
- $resp['msg'] = 'Failed to saved data. Error: '.$conn->error;
- }
- }
- }
- elseif($action == 'delete_student'){
- $delete = $conn->query("DELETE FROM `student_list` where id = '{$id}'");
- if($delete){
- $resp['status'] = 'success';
- $_SESSION['flashdata']['type'] = 'success';
- $_SESSION['flashdata']['msg'] = 'Data Field successfully deleted.';
- }else{
- $resp['status'] = 'failed';
- $resp['msg'] = 'Error: '.$conn->error;
- }
- }
DEMO VIDEO
There you go! You can now test the simple web application we created and see if we've met our goals for this tutorial. If you have encountered any errors, kindly review the scripts I provided above. You can also download the working source code I created for this tutorial.
I hope this PHP, jQuery, Ajax, and MySQL Database Tutorial will help you enhance your programming capabilities and you'll find this useful for your future PHP Projects.
Explore more on this website for more Programming Tutorials and Free Source Codes.
Happy Coding :)
Add new comment
- 2515 views