article

Showing posts with label web-development (PHP-MYSQL). Show all posts
Showing posts with label web-development (PHP-MYSQL). Show all posts

Tuesday, April 5, 2022

Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli

Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `multiplerow_members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `multiplerow_members` (`id`, `firstname`, `lastname`) VALUES
(1, 'Airi ', 'Sato'),
(2, 'Bourto', 'Usumaki');

ALTER TABLE `multiplerow_members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `multiplerow_members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<div class="row">
		<div class="col-md-12">
			<h2>Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli</h2>
			<h2>Members Table</h2>
			<div id="table"></div>
		</div>
	</div>
	<div class="row">
		<div class="col-md-8">
			<h2>Add Form</h2>
			<form id="addForm">
				<hr>
				<div class="row">
					<div class="col-md-2">
						<label style="position:relative; top:7px;">Firstname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" name="firstname[]" class="form-control">
					</div>
				</div>
				<div style="height:10px;"></div>
				<div class="row">
					<div class="col-md-2">
						<label style="position:relative; top:7px;">Lastname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" name="lastname[]" class="form-control">
					</div>
				</div>
				<hr>
				<div id="newrow"></div>
				<div class="row">
					<div class="col-md-12">
						<button type="button" id="save" class="btn btn-primary"> Save</button>
						<button type="button" id="newbutton" class="btn btn-primary"> Add New</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	showTable();

	$('#newbutton').click(function(){
		$('#newrow').slideDown();
		var newrow = '<hr>';
			newrow = '<div class="row">';
   		 	newrow += '<div class="col-md-2"><label style="position:relative; top:7px;">Firstname:</label></div>';
   		 	newrow += '<div class="col-md-10"><input type="text" name="firstname[]" class="form-control"></div>';
   		 	newrow += '</div>';
   		 	newrow += '<div style="height:10px;"></div>';
   		 	newrow += '<div class="row">';
   		 	newrow += '<div class="col-md-2"><label style="position:relative; top:7px;">Lastname:</label></div>';
   		 	newrow += '<div class="col-md-10"><input type="text" name="lastname[]" class="form-control"></div>';
   		 	newrow += '</div>';
   		 	newrow += '<hr>';	 	 
   		$('#newrow').append(newrow);	
	});

	$('#save').click(function(){
		var addForm = $('#addForm').serialize();
		$.ajax({
			type: 'POST',
			url: 'add.php',
			data: addForm,
			success:function(data){
				if(data==''){
					showTable();
					$('#addForm')[0].reset();
					$('#newrow').slideUp();
					$('#newrow').empty();
				}
				else{
					showTable();
					$('#addForm')[0].reset();
					$('#newrow').slideUp();
					$('#newrow').empty();
					alert('Rows with empty field are not added');
				}
				
			}
		});
	});

});

function showTable(){
	$.ajax({
		type: 'POST',
		url: 'fetch.php',
		data:{
			fetch: 1,
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
add.php
//add.php
<?php
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname = $_POST["firstname"];
 		$lastname = $_POST["lastname"];

 		for($count = 0; $count<count($firstname); $count++){
  			$firstname_clean = mysqli_real_escape_string($conn, $firstname[$count]);
  			$lastname_clean = mysqli_real_escape_string($conn, $lastname[$count]);

  			if($firstname_clean != '' && $lastname_clean != ''){
				$conn->query("insert into multiplerow_members (firstname, lastname) values ('".$firstname_clean."', '".$lastname_clean."')");
			}
			else{
				echo "1";
			}
 		}
	}

?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
			<table class="table table-bordered table-striped">
				<thead>
					<th>Firstname</th>
					<th>Lastname</th>
				</thead>
				<tbody>
					<?php
						include('conn.php');
						$query=$conn->query("select * from multiplerow_members");
						while($row=$query->fetch_array()){
							?>
							<tr>
								<td><?php echo $row['firstname']; ?></td>
								<td><?php echo $row['lastname']; ?></td>
							</tr>
							<?php
						}
					?>
				</tbody>
			</table>
		<?php
	}

?>

Saturday, April 2, 2022

Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli

Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

ALTER TABLE `carbrands`
  ADD PRIMARY KEY (`brand_id`);

ALTER TABLE `carbrands`
  MODIFY `brand_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
  
CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

ALTER TABLE `carmodels`
  ADD PRIMARY KEY (`model_id`),
  ADD KEY `industry_id` (`brand_id`);

ALTER TABLE `carmodels`
  MODIFY `model_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />   
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
</head>
<body>
<?php
include('conn.php');
?>
<div class="container">
 <h3 class="mt-4 text-center text-secondary">Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli</h3>
  <div class="row">
    <div class="col-sm-4">

      <h5 class="mt-4">Car Brand Name</h5>
       <select name="carbrand" id="carbrand" class="form-select">
        <?php 
              $sql = "SELECT * FROM carbrands";
              $query = mysqli_query($conn,$sql);
              while($row=mysqli_fetch_assoc($query))
              {
                echo '<option value="'.$row['brand_id'].'">'.$row["brand_name"].'</option>';
              }
        ?>
       </select>
	</div>
    <div class="col-sm-4">
      <h5 class="mt-4 ">Car Model</h5>
        <p id="loading" style="display:none">
           <img src="img/loader.gif"><span class="sr-only">Loading...</span>
        </p>
        <select  class="form-select"  name="select" id="show"  style="display:none;"></select>
	</div>
</div>
</div>
<script>
  $(document).ready(function(){
    $('#carbrand').change(function(){
      var Stdid = $('#carbrand').val(); 
       $.ajax({
          url:'fetch.php',
          type:'POST',
          data:{id:Stdid},
          success:function(response)
          {
            $('#loading').css('display','block');
            setTimeout(function()
            { 
                $('#show').html(response);
                $('#show').show();
                $('#loading').css('display','none');
            },3000);
          }
       });
    });
  });
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch.php
//fetch.php
<?php
  include('conn.php');

  $id = $_POST['id'];
  $sql = "SELECT * FROM carmodels WHERE brand_id= $id ";
  $result = mysqli_query($conn,$sql);

  $out='';
  while($row = mysqli_fetch_assoc($result)) 
  {   
     $out .=  '<option>'.$row['car_models'].'</option>'; 
  }
   echo $out;
?>

Jquery Ajax Dependent Dropdown Select with PHP Mysqli

Jquery Ajax Dependent Dropdown Select with PHP Mysqli

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

ALTER TABLE `carbrands`
  ADD PRIMARY KEY (`brand_id`);

ALTER TABLE `carbrands`
  MODIFY `brand_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
  
CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

ALTER TABLE `carmodels`
  ADD PRIMARY KEY (`model_id`),
  ADD KEY `industry_id` (`brand_id`);

ALTER TABLE `carmodels`
  MODIFY `model_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;


index.php
//index.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>Jquery Ajax Dependent Dropdown Select with PHP Mysqli</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />   
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
</head>
<body>
<?php
include('conn.php');
?>
 <div class="container mt-4">
 <h4 class="text-center">Jquery Ajax Dependent Dropdown Select with PHP Mysqli</h4><br>
   <div class="row">
    <div class="col-sm-4">
      <h6>Car Brand Name</h6>
        <select class="form-select" name="select" id="selectID">
        <option>Select Option</option>

        <?php $sql = "SELECT * FROM carbrands";
            $result = mysqli_query($conn,$sql);
            while($row = mysqli_fetch_assoc($result)) {?>
            <option value="<?php echo $row['brand_id'] ?>"><?php echo $row['brand_name'] ?></option>
            <?php }?>

        </select>
     </div> 

     <div class="col-sm-4">  
     <h6>Car Model</h6>
      <select  class="form-select"  name="select" id="show"></select>
    </div>
   
   </div>
 </div>  
<script>
  $(document).ready(function(){
     $('#selectID').change(function(){
      var Stdid = $('#selectID').val(); 

      $.ajax({
        type: 'POST',
        url: 'fetch.php',
        data: {id:Stdid},  
        success: function(data)  
         {
            $('#show').html(data);
         }
        });
     });
  });
</script> 
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch.php
//fetch.php
<?php
  include('conn.php');

  $id = $_POST['id'];
  $sql = "SELECT * FROM carmodels WHERE brand_id= $id ";
  $result = mysqli_query($conn,$sql);

  $out='';
  while($row = mysqli_fetch_assoc($result)) 
  {   
     $out .=  '<option>'.$row['car_models'].'</option>'; 
  }
   echo $out;
?>

Load More Data using Jquery Ajax with PHP MySQLi

Load More Data using Jquery Ajax with PHP MySQLi


Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `country` (`id`, `country`) VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia'),
(15, 'Austria'),
(16, 'Azerbaijan'),
(17, 'Bahamas'),
(18, 'Bahrain'),
(19, 'Bangladesh'),
(20, 'Barbados');

ALTER TABLE `country`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;


index.php
//index.php
<!DOCTYPE html>  
<html>  
<head>  
      <title>Load More Data using Jquery Ajax with PHP MySQLi</title>  
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />   
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>  
</head>  
<body>  
      <div class="container">   
        <div class="row">
              <h2 align="center">Load More Data using Jquery Ajax with PHP MySQLi</h2>
              <div id="loadtable">  
                  <?php
                    $lastid='';
                    include('conn.php');
                    $query=mysqli_query($conn,"select * from country order by id asc limit 5");
                    while($row=mysqli_fetch_array($query)){
                        ?>
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="btn btn-success" style="margin:10px;width:50%;"><?php echo $row['country']; ?></div>
                            </div>
                        </div>
                        <?php
                      $lastid=$row['id'];
                    }

                  ?>
                  <div id="remove">
                  <div class="row">
                      <div class="col-lg-12">
                      <button type="button" name="loadmore" id="loadmore" data-id="<?php echo $lastid; ?>" class="btn btn-primary">See More</button>
                      </div>
                  </div>
                  </div>  
                </div>  
          </div>  
      </div>

<script>
$(document).ready(function(){  
      $(document).on('click', '#loadmore', function(){  
           var lastid = $(this).data('id');  
           $('#loadmore').html('Loading...');  
           $.ajax({  
                url:"load_data.php",  
                method:"POST",  
                data:{
                    lastid:lastid,
                },  
                dataType:"text",  
                success:function(data)  
                {  
                     if(data != '')  
                     {  
                          $('#remove').remove();  
                          $('#loadtable').append(data);  
                     }  
                     else  
                     {  
                          $('#loadmore').html('No more data to show');  
                     }  
                }  
           });  
      });  
 }); 
</script>  
</body>  
</html>  
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
load_data.php
//load_data.php
<?php  
     sleep(1);  
     include('conn.php');
     if(isset($_POST['lastid'])){
          $lastid=$_POST['lastid'];
          $query=mysqli_query($conn,"select * from country where id > '$lastid' order by id asc limit 5");
  
          if(mysqli_num_rows($query) > 0){  
          while($row = mysqli_fetch_array($query)){  
               ?>
                    <div class="row">
                         <div class="col-lg-12">
                              <div class="btn btn-success" style="margin:10px;width:50%;"><?php echo $row['country']; ?></div>
                         </div>
                    </div>
               <?php
               $lastid=$row['id'];
          }
          ?>
          <div id="remove"> 
          <div id="remove_row" class="row">
               <div class="col-lg-12">
                    <button type="button" name="loadmore" id="loadmore" data-id="<?php echo $lastid; ?>" class="btn btn-primary">See More</button>
               </div>
          </div>
          </div> 
          <?php 
          }  
     }
?>

Monday, March 28, 2022

Submit Form using Jquey AJAX with PHP MySQLi

Submit Form using Jquey AJAX with PHP MySQLi

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Submit Form using Jquey AJAX with PHP MySQLi</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<div class="card card-body bg-light">
		<div class="row">
			<div class="col-lg-12">
				<h2><center>Submit Form using Jquey AJAX with PHP MySQLi</center></h2>
			</div>
		</div>
		<form id="form">
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Firstname:</label>
				<input type="text" name="firstname" class="form-control">
			</div>
		</div>
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Lastname:</label>
				<input type="text" name="lastname" class="form-control">
			</div>
		</div>
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Address:</label>
				<input type="text" name="address" class="form-control">
			</div>
		</div>
		</form>
		<div class="row">
			<div class="col-lg-12">
				<button type="button" class="btn btn-primary pull-right" id="submit">Submit</button>
			</div>
		</div>
	</div>
	<div class="row" style="margin-top:20px;">
		<div id="table">
		</div>
	</div>
</div>
<script>
$(document).ready(function(){

	showTable();

	$('#submit').click(function(){
		var form=$('#form').serialize();
		$.ajax({
			url:"add.php",
			method:"POST",
			data:form,
			success:function(){
				showTable();
				$('#form')[0].reset();
			} 
		});
	});
});

function showTable(){
	$.ajax({
		url:"fetch.php",
		method:"POST",
		data:{
			fetch: 1,
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
 
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
		<table class="table table-bordered table-striped">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
			</thead>
			<tbody>
				<?php
					$query=mysqli_query($conn,"select * from members order by id desc");
					while($row=mysqli_fetch_array($query)){
					?>
					<tr>
						<td><?php echo $row['firstname']; ?></td>
						<td><?php echo $row['lastname']; ?></td>
						<td><?php echo $row['address']; ?></td>
					</tr>
					<?php
					}
				?>
			</tbody>
		</table>
		<?php	
	}
?>
add.php
//add.php
<?php 
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		$address=$_POST['address'];

		mysqli_query($conn,"insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	}
?>

Thursday, March 24, 2022

Jquery Ajax Image Upload with PHP MySQLi

Jquery Ajax Image Upload with PHP MySQLi

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `tbluploadphoto` (
  `photoid` int(11) NOT NULL,
  `location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `tbluploadphoto`
  ADD PRIMARY KEY (`photoid`);


ALTER TABLE `tbluploadphoto`
  MODIFY `photoid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


index.php
//index.php
<!DOCTYPE html>
<html>
<head>
    <title>Jquery Ajax Image Upload with PHP MySQLi</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
  <div class="row">
      <form>
        <h2 align="center" style="color:blue">Jquery Ajax Image Upload with PHP MySQLi</h2>
        <label>Select Image:</label>
        <input type="file" name="file" id="file"><br>
        <button type="button" id="upload_button" class="btn btn-primary">Upload</button>
      </form>
  </div>
  <div style="width:80%; padding:auto; margin:auto;">
      <div id="imagelist"></div>
  </div>
</div>
<script>
$(document).ready(function(){

  showPhoto();

  $(document).on('click', '#upload_button', function(){
	  
    var name = document.getElementById("file").files[0].name;
    var form_data = new FormData();
    var ext = name.split('.').pop().toLowerCase();
    if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1){
      alert("Invalid Image File");
    }
	
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("file").files[0]);
    var f = document.getElementById("file").files[0];
    var fsize = f.size||f.fileSize;
	
    if(fsize > 2000000){
      alert("Image File Size is very big");
    }else{
		form_data.append("file", document.getElementById('file').files[0]);
		$.ajax({
		  url:"upload.php",
		  method:"POST",
		  data: form_data,
		  contentType: false,
		  cache: false,
		  processData: false,   
		  success:function(){
			showPhoto();
		  }
		});
    }
	
  });
});

function showPhoto(){
  $.ajax({
      url:"fetch_photo.php",
      method:"POST",
      data:{
        fetch:1,
      },
      success:function(data){
        $('#imagelist').html(data);
      }
    });
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch_photo.php
//fetch_photo.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		$inc=4;
		$query=mysqli_query($conn,"select * from tbluploadphoto");
		while($row=mysqli_fetch_array($query)){
		$inc = ($inc == 4) ? 1 : $inc+1; 
		if($inc == 1) echo '<div class="row">';  
 			?>
				<div class="col-lg-3"><img src="<?php echo $row['location']?>" style="height:200px; width:100%;"></div>
 
			<?php
		if($inc == 4) echo '</div>';
		}
		if($inc == 1) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div><div class="col-lg-3"></div></div>'; 
		if($inc == 2) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div></div>'; 
		if($inc == 3) echo '<div class="col-lg-3"></div></div>'; 
	}
?>
uppload.php
//uppload.php
<?php
include('conn.php');
if($_FILES["file"]["name"] != '')
{
 	$newFilename = time() . "_" . $_FILES["file"]["name"];
 	$location = 'upload/' . $newFilename;  
	move_uploaded_file($_FILES["file"]["tmp_name"], $location);
 	
 	mysqli_query($conn,"insert into tbluploadphoto (location) values ('$location')");
}
?>

Tuesday, March 22, 2022

PHP MySQLi Delete Multiple Rows using Checkbox

PHP MySQLi Delete Multiple Rows using Checkbox

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP MySQLi Delete Multiple Rows using Checkbox</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
	<div class="row" style="margin-top:20px;margin-bottom:20px;">
	<span style="font-size:25px; color:blue"><center><strong>PHP MySQLi Delete Multiple Rows using Checkbox</strong></center></span>	
		<div style="height:20px;"></div>
		<table class="table table-striped table-bordered table-hover">
			<thead>
				<th></th>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
				
			</thead>
			<form method="POST" action="delete.php">
			<tbody>
			<?php
				include('conn.php');
				
				$query=mysqli_query($conn,"select * from members");
				while($row=mysqli_fetch_array($query)){
					?>
					<tr>
						<td align="center"><input type="checkbox" value="<?php echo $row['id']; ?>" name="userid[]"></td>
						<td><?php echo $row['firstname']; ?></td>
						<td><?php echo $row['lastname']; ?></td>
						<td><?php echo $row['address']; ?></td>		
					</tr>
					<?php
				}
			
			?>
			</tbody>
		</table>
			<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnew" style="width:200px;"> Add New</button> ||
			<button type="submit" class="btn btn-danger" style="width:200px;"> Delete</button>
			</form>
	</div>
	<?php include('modal.php'); ?>
</div>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
modal.php
//modal.php
<!-- Modal -->
<div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="addnew" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addnew">Add New</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
				<form method="POST" action="addnew.php">
					<div class="row">
						<div class="col-lg-2">
							<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
						</div>
						<div class="col-lg-10">
							<input type="text" class="form-control" name="firstname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-lg-2">
							<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
						</div>
						<div class="col-lg-10">
							<input type="text" class="form-control" name="lastname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-lg-2">
							<label class="control-label" style="position:relative; top:7px;">Address:</label>
						</div>
						<div class="col-lg-10">
							<input type="text" class="form-control" name="address">
						</div>
					</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save</button>
		</form>
      </div>
    </div>
  </div>
</div>
addnew.php
//addnew.php
<?php
	include('conn.php');
	
	$firstname=$_POST['firstname'];
	$lastname=$_POST['lastname'];
	$address=$_POST['address'];
	
	mysqli_query($conn,"insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	header('location:index.php');
?>
delete.php
//delete.php
<?php
	include('conn.php');
	
	if(isset($_POST['userid'])){
		foreach ($_POST['userid'] as $id):
			mysqli_query($conn,"delete from members where id='$id'");
		endforeach;
		
		header('location:index.php');
	}
	else{
		?>
		<script>
			window.alert('Please check user to Delete');
			window.location.href='index.php';
		</script>
		<?php
	}
?>

Thursday, March 10, 2022

PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX with Bootstrap 5 Modal

PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX with Bootstrap 5 Modal

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Bootstrap icons
https://icons.getbootstrap.com/#install
https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Caesar', 'Vance', 'New York');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
	<body>
<div class="container">
	<div class="row"><p><h1>PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX with Bootstrap 5 Modal</h1></p></div>
	<div style="margin-left:auto; margin-right:auto; padding:auto; width:70%;">
		<p class="pull-right"><a id="add" style="cursor:pointer;" class="btn btn-primary"><i class="bi bi-clipboard2-plus-fill"></i> Add New</a></p>

		<div id="table"></div>
		<div id="alert" class="alert alert-success" style="display:none;">
			<center><span id="alerttext"></span></center>
		</div>
	</div>
<?php include('modal.php'); ?>
</div>
<script>
$(document).ready(function(){
	showTable();

	//add
	$('#add').click(function(){
		$('#addnew').modal('show');
		$('#addForm')[0].reset();
	});

	$('#addbutton').click(function(){
		var first = $('#firstname').val();
		var last = $('#lastname').val();
		var address = $('#address').val();
		if(first!='' && last!==''){
			var addForm = $('#addForm').serialize();
			$.ajax({
				type: 'POST',
				url: 'add.php',
				data: addForm,
				success:function(){
					$('#addnew').modal('hide');
					$('#addForm')[0].reset();
					showTable();
					$('#alert').slideDown();
					$('#alerttext').text('Member Added Successfully');
				}
			});
		}
		else{
			alert('Please input both Fields')
		}
		
	});
	//
	//edit
	$(document).on('click', '.edit', function(){
		var id = $(this).data('id'); 
		var first = $('#first'+id).text();
		var last = $('#last'+id).text(); 
		var address = $('#address'+id).text(); 
		$('#editmem').modal('show');
		$('#eid').val(id);
		$('#efirstname').val(first);
		$('#elastname').val(last);
		$('#eaddress').val(address);
	});

	$('#editbutton').click(function(){
		var id = $('#eid').val(); //alert(id);
		var editForm = $('#editForm').serialize();
		$.ajax({
			type: 'POST',
			url: 'edit.php',
			data: editForm + "&id="+id,
			success:function(response){
				console.log(response);
				$('#editmem').modal('hide');
				$('#editForm')[0].reset();
				showTable();
				$('#alert').slideDown();
				$('#alerttext').text('Member Updated Successfully');
			}
		});
	});
	//
	//delete
	$(document).on('click', '.delete', function(){
		var id = $(this).data('id');
		var first = $('#first'+id).text();
		$('#delmem').modal('show');
		$('#dfirstname').text(first);
		$('#delbutton').val(id);
	});

	$('#delbutton').click(function(){
		var id = $(this).val();
		$.ajax({
			type: 'POST',
			url: 'delete.php',
			data: {
				id: id,
			},
			success:function(){
				$('#delmem').modal('hide');
				showTable();
				$('#alert').slideDown();
				$('#alerttext').text('Member Deleted Successfully');
			}
		});
	});

});

function showTable(){
	$.ajax({
		type: 'POST',
		url: 'fetch.php',
		data: {
			fetch: 1
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
		<table class="table table-striped table-bordered table-hover">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
				<th>Action</th>
			</thead>
			<tbody>
			<?php
				$query=$conn->query("select * from members");
				while($row=$query->fetch_array()){
					?>
					<tr>
						<td><span id="first<?php echo $row['id']; ?>"><?php echo $row['firstname']; ?></span></td>
						<td><span id="last<?php echo $row['id']; ?>"><?php echo $row['lastname']; ?></span></td>
						<td><span id="address<?php echo $row['id']; ?>"><?php echo $row['address']; ?></span></td>
						<td>
							<a style="cursor:pointer;" class="btn btn-warning edit" data-id="<?php echo $row['id']; ?>"><i class="bi bi-pencil"></i> Edit</a> || 
							<a style="cursor:pointer;" class="btn btn-danger delete" data-id="<?php echo $row['id']; ?>"><i class="bi bi-trash"></i> Delete</a>
						</td>
					</tr>
					<?php
				}
			
			?>
			</tbody>
		</table>
		<?php
	}
?>
add.php
//add.php
<?php
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		$address=$_POST['address'];

		$conn->query("insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	}
?>
modal.php
//modal.php
<!-- Add New -->
    <div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
			      <div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">Add New Member</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				  </div>
                <div class="modal-body">
				<div class="container-fluid">
				<form id="addForm">
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="firstname" id="firstname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="lastname" id="lastname">
						</div>
					</div>				
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Address:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="address" id="address">
						</div>
					</div>
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="addbutton" class="btn btn-primary"> Save</a>
				</form>
                </div>
				
            </div>
        </div>
    </div>

<!-- Edit -->
	<div class="modal fade" id="editmem" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">Edit Member</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
                <div class="modal-body">
				<div class="container-fluid">
				<form id="editForm">
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="efirstname" id="efirstname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2"><input type="hidden" name="eid" id="eid">
							<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="elastname" id="elastname">
						</div>
					</div>					
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Address:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="eaddress" id="eaddress">
						</div>
					</div>
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="editbutton" class="btn btn-warning"> Update</a>
				</form>
                </div>
				
            </div>
        </div>
    </div>

<!-- Delete -->
    <div class="modal fade" id="delmem" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">Delete Member</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
                <div class="modal-body">
				<div class="container-fluid">
					<h5><center>Firstname: <strong><span id="dfirstname"></span></strong></center></h5> 
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="delbutton" class="btn btn-danger"> Delete</button>
                </div>
				
            </div>
        </div>
    </div>
edit.php
//edit.php
<?php
	include('conn.php');
	if(isset($_POST['efirstname'])){
		$firstname=$_POST['efirstname'];
		$lastname=$_POST['elastname'];
		$address=$_POST['eaddress'];
		$id=$_POST['id'];

		$conn->query("update members set firstname='$firstname', lastname='$lastname', address='$address' where id='$id'");

		$response[] = array("firstname"=>$firstname,"lastname" => $lastname,"address" => $address,"member_id" => $id);
		echo json_encode($response);
	}
?>
delete.php
//delete.php
<?php
	include('conn.php');
	if(isset($_POST['id'])){
		$id=$_POST['id'];

		$conn->query("delete from members where id='$id'");
	}
?>

Monday, March 7, 2022

PHP PDO Mysql Check username availability with Jquery AJAX

PHP PDO Mysql Check username availability with Jquery AJAX

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css
https://getbootstrap.com/docs/5.0/components/modal/

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
checkusername.php
//checkusername.php
<!doctype html>
<html>
 <head>
<title>PHP PDO Mysql Check username availability with Jquery AJAX </title>
<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />		
<script src = "https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>	
</head>
<body>
	<div class="container">
		<div class="row"><p><h1>PHP PDO Mysql Check username availability with Jquery AJAX </h1></p>
			<label class="form-label">Enter UserName</label>
			<input type="text" id="txt_username" class="form-control" name="txt_username" placeholder="Enter Username">
			<!-- Response -->
            <div id="uname_response" ></div>
		</div>
	</div>
    <script type='text/javascript'>
            $(document).ready(function(){

                $("#txt_username").keyup(function(){

                    var username = $(this).val().trim();

                    if(username != ''){

                        $.ajax({
                            url: 'ajaxfile.php',
                            type: 'post',
                            data: {username:username},
                            success: function(response){
                                console.log(response);
                                // Show response
                                $("#uname_response").html(response);

                            }
                        });
                    }else{
                        $("#uname_response").html("");
                    }

                });

            });
	</script>
</body>
</html>
ajaxfile.php
//ajaxfile.php
<?php

$server = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";

// Create connection
try{
   $conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password");
   $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
   die('Unable to connect with the database');
}

if(isset($_POST['username'])){
	$username = $_POST['username'];

	// Check username
	$stmt = $conn->prepare("SELECT count(*) as cntUser FROM users WHERE username=:username");
	$stmt->bindValue(':username', $username, PDO::PARAM_STR);
	$stmt->execute(); 
	$count = $stmt->fetchColumn();
	//echo $count;
	
	if($count == 0){
		$response = "<span style='color: green;'>Available.</span>";	
	}else{
		$response = "<span style='color: red;'>Not Available.</span>";
	}	
	
	echo $response;
	exit;
}

PHP OOP Mysqli CRUD (Create Read Update and Delete)



Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css
https://getbootstrap.com/docs/5.0/components/modal/

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Bootstrap icons
https://icons.getbootstrap.com/#install
https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
index.php
//index.php
<?php 
	include('conn.php');
    session_start();
?>
<!DOCTYPE html>
<html>
<head>
	<title>PHP - OOP CRUD Operation</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container">
	<div style="height:50px;"></div>
	<div class="well" style="margin-left:auto; margin-right:auto; padding:auto; width:70%;">
		<span style="font-size:25px; color:blue"><strong>PHP OOP Mysqli CRUD (Create Read Update and Delete)</strong></span>	
		<span class="pull-right">
		<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnew">
		<i class="bi bi-clipboard2-plus-fill"></i> Add Newl
		</button>
		</span>
		<div style="height:15px;"></div>
		<table class="table table-striped table-bordered table-hover">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
				<th>Action</th>
			</thead>
			<tbody>
			<?php
				$query=$conn->query("select * from members");
				while($row=$query->fetch_array()){
					?>
					<tr>
						<td><?php echo $row['firstname']; ?></td>
						<td><?php echo $row['lastname']; ?></td>
						<td><?php echo $row['address']; ?></td>
						<td>
							<button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $row['id']; ?>"><i class="bi bi-pencil"></i> Edit</button>  ||
							<button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $row['id']; ?>"><i class="bi bi-trash"></i> Delete</button>
							<?php include('modal.php'); ?>
						</td>
					</tr>
					<?php
				}
			
			?>
			</tbody>
		</table>
		<?php
			if(isset($_SESSION['msg'])){
				?>
					<div class="alert alert-success">
						<center><?php echo $_SESSION['msg']; ?></center>
					</div>
				<?php
				unset($_SESSION['msg']);
			}
		?>
	</div>
	<?php include('add_modal.php'); ?>
</div>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
add_modal.php
//add_modal.php
<!-- Add New -->
<div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
			<form method="POST" action="addnew.php">
				<div class="row">
					<div class="col-md-2">
						<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" class="form-control" name="firstname">
					</div>
				</div>
				<div style="height:10px;"></div>
				<div class="row">
					<div class="col-md-2">
						<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" class="form-control" name="lastname">
					</div>
				</div>
				<div style="height:10px;"></div>
				<div class="row">
					<div class="col-md-2">
						<label class="control-label" style="position:relative; top:7px;">Address:</label>
					</div>
					<div class="col-md-10">
						<input type="text" class="form-control" name="address">
					</div>
				</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save changes</button>
		</form>
      </div>
    </div>
  </div>
</div>
addnew.php
//addnew.php
<?php
	include('conn.php');
	session_start();
	
	$firstname=$_POST['firstname'];
	$lastname=$_POST['lastname'];
	$address=$_POST['address'];
	
	$conn->query("insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	$_SESSION['msg']="Member Added Succesfully";
	header('location:index.php');
?>
modal.php
//modal.php
<!-- Delete -->
	<div class="modal fade" id="deleteModal<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
			   <div class="modal-header">
				<h5 class="modal-title" id="exampleModalLabel">Delete Member</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			   </div>
                <div class="modal-body">
				<?php
					$del=mysqli_query($conn,"select * from members where id='".$row['id']."'");
					$drow=mysqli_fetch_array($del);
				?>
				<div class="container-fluid">
					<h5><center>Firstname: <strong><?php echo $drow['firstname']; ?></strong></center></h5> 
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger"> Delete</a>
                </div>
				
            </div>
        </div>
    </div>
<!-- /.modal -->

<!-- Edit -->
	<div class="modal fade" id="editModal<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
			   <div class="modal-header">
				<h5 class="modal-title" id="exampleModalLabel">Update Member</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			  </div>
                <div class="modal-body">
				<?php
					$edit=$conn->query("select * from members where id='".$row['id']."'");
					$erow=$edit->fetch_array();
				?>
				<div class="container-fluid">
				<form method="POST" action="edit.php?id=<?php echo $erow['id']; ?>">
					<div class="row">
						<div class="col-md-2">
							<label style="position:relative; top:7px;">Firstname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" name="firstname" class="form-control" value="<?php echo $erow['firstname']; ?>">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label style="position:relative; top:7px;">Lastname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" name="lastname" class="form-control" value="<?php echo $erow['lastname']; ?>">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label style="position:relative; top:7px;">Address:</label>
						</div>
						<div class="col-md-10">
							<input type="text" name="address" class="form-control" value="<?php echo $erow['address']; ?>">
						</div>
					</div>
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning"> Save</button>
                </div>
				</form>
            </div>
        </div>
    </div>
<!-- /.modal -->
edit.php
//edit.php
<?php
	include('conn.php');
	session_start();

	$id=$_GET['id'];
	$firstname=$_POST['firstname'];
	$lastname=$_POST['lastname'];
	$address=$_POST['address'];
	
	$conn->query("update members set firstname='$firstname', lastname='$lastname', address='$address' where id='$id'");
	$_SESSION['msg']="Member Updated Succesfully";
	header('location:index.php');
?>
delete.php
//delete.php
<?php
	include('conn.php');
	session_start();

	$id=$_GET['id'];

	$conn->query("delete from members where id='$id'");
	$_SESSION['msg']="Member Deleted Succesfully";
	header('location:index.php');
?>

Saturday, February 26, 2022

PHP Mysqli CRUD with JQuery AJAX and Bootstrap 5

PHP Mysqli CRUD (Create, Read, Update and Delete) with JQuery AJAX and Bootstrap 5

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Bootstrap icons
https://icons.getbootstrap.com/#install
https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css
index.php
//index.php
<?php
	include('conn.php');
?>
<!DOCTYPE html>
<html lang = "en">
	<head>
		<meta charset = "UTF-8" name = "viewport" content = "width-device=width, initial-scale=1" />
		<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
		<title>PHP Mysqli CRUD with JQuery AJAX and Bootstrap 5</title>
	</head>
<body>
	<div style="height:30px;"></div>
	<div class = "row">	
		<div class = "col-md-3">
		</div>
		<div class = "col-md-6 well">
			<div class="row">
                <div class="col-lg-12">
                    <center><h2 class = "text-primary">PHP Mysqli CRUD with JQuery AJAX and Bootstrap 5</h2></center>
					<hr>
				<div>
					<form>
						<div class="mb-3">
							<label>Firstname:</label>
							<input type  = "text" id = "firstname" class = "form-control">
						</div>
						<div class="mb-3">
							<label>Lastname:</label>
							<input type  = "text" id = "lastname" class = "form-control">
						</div>
						<div class="mb-3">
							<button type = "button" id="addnew" class = "btn btn-primary"><i class="bi bi-clipboard2-plus-fill"></i> Add</button>
						</div>
					</form>
				</div>
                </div>
            </div><br>
			<div class="row">
			<div id="userTable"></div>
			</div>
		</div>
	</div>
</body>
<script src = "https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>	
<script src = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script type = "text/javascript">
	$(document).ready(function(){
		showUser();
		//Add New
		$(document).on('click', '#addnew', function(){
			if ($('#firstname').val()=="" || $('#lastname').val()==""){
				alert('Please input data first');
			}
			else{
			$firstname=$('#firstname').val();
			$lastname=$('#lastname').val();				
				$.ajax({
					type: "POST",
					url: "addnew.php",
					data: {
						firstname: $firstname,
						lastname: $lastname,
						add: 1,
					},
					success: function(){
						showUser();
					}
				});
			}
		});
		//Delete
		$(document).on('click', '.delete', function(){
			$id=$(this).val();
				$.ajax({
					type: "POST",
					url: "delete.php",
					data: {
						id: $id,
						del: 1,
					},
					success: function(){
						showUser();
					}
				});
		});
		//Update
		$(document).on('click', '.updateuser', function(){
			$uid=$(this).val();
			$('#edit'+$uid).modal('hide');
			$('body').removeClass('modal-open');
			$('.modal-backdrop').remove();
			$ufirstname=$('#ufirstname'+$uid).val();
			$ulastname=$('#ulastname'+$uid).val();
				$.ajax({
					type: "POST",
					url: "update.php",
					data: {
						id: $uid,
						firstname: $ufirstname,
						lastname: $ulastname,
						edit: 1,
					},
					success: function(){
						showUser();
					}
				});
		});
	
	});
	
	//Showing our Table
	function showUser(){
		$.ajax({
			url: 'show_user.php',
			type: 'POST',
			async: false,
			data:{
				show: 1
			},
			success: function(response){
				$('#userTable').html(response);
			}
		});
	}
	
</script>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
addnew.php
//addnew.php
<?php
	include('conn.php');
	if(isset($_POST['add'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		
		mysqli_query($conn,"insert into usertble (firstname, lastname) values ('$firstname', '$lastname')");
	}
?>
show_user.php
//show_user.php
<?php
	include('conn.php');
	if(isset($_POST['show'])){
		?>
		<table class = "table table-bordered alert-success table-hover">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Action</th>
			</thead>
				<tbody>
					<?php
						$quser=mysqli_query($conn,"select * from usertble");
						while($urow=mysqli_fetch_array($quser)){
							?>
								<tr>
									<td><?php echo $urow['firstname']; ?></td>
									<td><?php echo $urow['lastname']; ?></td>
									<td><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $urow['userid']; ?>"><i class="bi bi-pencil"></i> Edit</button> | <button class="btn btn-danger delete" value="<?php echo $urow['userid']; ?>"><i class="bi bi-trash"></i> Delete</button>
									<?php include('edit_modal.php'); ?>
									</td>
								</tr>
							<?php
						}
					
					?>
				</tbody>
			</table>
		<?php
	}

?>
edit_modal.php
//edit_modal.php
<div class="modal fade" id="edit<?php echo $urow['userid']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	<?php
		$n=mysqli_query($conn,"select * from `user` where userid='".$urow['userid']."'");
		$nrow=mysqli_fetch_array($n);
	?>
  <div class="modal-dialog" role="document">
    <div class="modal-content">
		<div class = "modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
			<center><h3 class = "text-success modal-title">Update Member</h3></center>
		</div>
		<form>
		<div class="modal-body">
			Firstname: <input type="text" value="<?php echo $nrow['firstname']; ?>" id="ufirstname<?php echo $urow['userid']; ?>" class="form-control">
			Lastname: <input type="text" value="<?php echo $nrow['lastname']; ?>" id="ulastname<?php echo $urow['userid']; ?>" class="form-control">
		</div>
		<div class="modal-footer">
			<button type="button" class="btn btn-default" data-dismiss="modal"><span class = "glyphicon glyphicon-remove"></span> Cancel</button> | <button type="button" class="updateuser btn btn-success" value="<?php echo $urow['userid']; ?>"><span class = "glyphicon glyphicon-floppy-disk"></span> Save</button>
		</div>
		</form>
    </div>
  </div>
</div>
update.php
//update.php
<?php
	include('conn.php');
	if(isset($_POST['edit'])){
		$id=$_POST['id'];
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		
		mysqli_query($conn,"update usertble set firstname='$firstname', lastname='$lastname' where userid='$id'");
	}
?>
//delete.php
<?php
	include('conn.php');
	if(isset($_POST['del'])){
		$id=$_POST['id'];
		mysqli_query($conn,"delete from usertble where userid='$id'");
	}
?>

Thursday, February 24, 2022

PHP Mysqli Simple Login Session with Validation

PHP Mysqli Simple Login Session with Validation

CREATE TABLE `userlogin` (
  `userid` int(11) NOT NULL,
  `username` varchar(30) NOT NULL,
  `password` varchar(30) NOT NULL,
  `fullname` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `userlogin` (`userid`, `username`, `password`, `fullname`) VALUES
(1, 'cairocoders', '123456', 'Cairocoders Ednalan');

ALTER TABLE `userlogin`
  ADD PRIMARY KEY (`userid`);

ALTER TABLE `userlogin`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>PHP Mysqli Simple Login Session with Validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />  
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.message {color: #FF0000;}
</style>
</head>
<body>
<?php
$Message = $ErrorUname = $ErrorPass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
    $username = check_input($_POST["username"]);
	
    if (!preg_match("/^[a-zA-Z0-9_]*$/",$username)) {
      $ErrorUname = "Space and special characters not allowed but you can use underscore(_)."; 
    }
	else{
		$fusername=$username;
	}
 
	$fpassword = check_input($_POST["password"]);

  if ($ErrorUname!=""){
	$Message = "Login failed! Errors found";
  }
  else{
  include('conn.php');
  
  $query=mysqli_query($conn,"select * from userlogin where username='$fusername' && password='$fpassword'");
  $num_rows=mysqli_num_rows($query);
  $row=mysqli_fetch_array($query);
  
  if ($num_rows>0){
	  $Message = "Login Successful!";
  }
  else{
	$Message = "Login Failed! User not found";
  }
  
  }
}

function check_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<section class="login">
<div class="container">
	<div class="row justify-content-center">
		<div class="col-md-6 text-center mb-5">
			<h2 class="heading-section">PHP Mysqli Simple Login Session with Validation</h2>
		</div>
	</div>
	<div class="row justify-content-center">
		<div class="col-md-7 col-lg-5">
			<div class="p-4 p-md-5">
			<div class="d-flex">
				<div class="w-100">
				<h3 class="mb-4">Sign In</h3>
				</div>
				<div class="w-100">
				<p class="justify-content-end">
				<a href="#" class="align-items-center justify-content-center"><span class="fa fa-facebook"></span></a>
				<a href="#" class="align-items-center justify-content-center"><span class="fa fa-twitter"></span></a>
				</p>
				</div>
			</div>
			<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
				<p><span class="message">* required field.</span></p>
				<div class="form-group mt-3">
					<input type="text" name="username" class="form-control" required>
					<label class="form-control-placeholder" for="username">Username</label>
					<span class="message">* <?php echo $ErrorUname;?></span>
				</div>
				<div class="form-group">
					<input type="password" name="password" class="form-control" required>
					<label class="form-control-placeholder" for="password">Password</label>
					<span class="message">* <?php echo $ErrorPass;?></span>
					<span class="fa fa-fw fa-eye"></span>
				</div>
				<div class="form-group">
					<button type="submit" class="form-control btn btn-primary rounded submit px-3">Sign In</button>
				</div>
				<span class="message">
				<?php
					if ($Message=="Login Successful!"){
						echo $Message;
						echo 'Welcome, '.$row['fullname'];
					}
					else{
						echo $Message;
					}

				?>
				</span>
				<div class="form-group d-md-flex">
					<div class="w-50 text-left">
					<label class="checkbox-primary mb-0">Remember Me
					<input type="checkbox" checked>
					<span class="checkmark"></span>
					</label>
					</div>
					<div class="w-50 text-md-right">
					<a href="#">Forgot Password</a>
					</div>
				</div>
			</form>
			<p class="text-center">Not a member? <a data-toggle="tab" href="#signup">Sign Up</a></p>
			</div>
		</div>
	</div>
</div>
</section>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

Monday, January 31, 2022

PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)

PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/getting-started/introduction/

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

https://datatables.net/

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `mobile` varchar(20) NOT NULL,
  `city` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `username`, `email`, `mobile`, `city`) VALUES
(7, 'Airi Satou', 'AiriSatou@gmail.com', '8887919632', 'Tokyo'),
(8, 'Angelica Ramos', 'AngelicaRamos@gmail.com', '8887919632', 'London'),
(9, 'Ashton Cox', 'AshtonCox@gmail.com', '8887919632', 'San Francisco'),
(10, 'Bradley Greer', 'BradleyGreer@gmail.com', '434334', 'London'),
(11, 'Brenden Wagner', 'BrendenWagner@gmail.com', '434334', 'San Francisco'),
(12, 'Brielle Williamson', 'BrielleWilliamson@gmail.com', '434334', 'New York'),
(13, 'Bruno Nash', 'BrunoNash@gmail.com', '9988999999', 'London'),
(15, 'Caesar Vance', 'CaesarVance@gmail.com', '8127956219', 'New York'),
(16, 'Cara Stevens', 'CaraStevens@gmail.com', '8127956219', 'New York'),
(18, 'Cedric Kelly', 'CedricKelly@gmail.com', '8127956219', 'Edinburgh'),
(19, 'Charde Marshall', 'ChardeMarshall@Gmail.com', '5464654654', 'San Francisco'),
(20, 'Colleen Hurst', 'ColleenHurst@Gmail.com', '5465465465', 'San Francisco'),
(21, 'Garrett Winters', 'GarrettWinters@gmail.com', '346546465', 'Olongapo City');

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
index.php
//index.php
<?php include('connection.php');?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css"/>
  <title>PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)</title>
  <style type="text/css">
    .btnAdd {
      text-align: right;
      width: 83%;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
<div class="container-fluid">
    <h2 class="text-center">PHP Mysqli Datatables Server Side CRUD Ajax (Create, Read, Update and Delete)</h2>
    <div class="row">
      <div class="container">
        <div class="btnAdd">
         <a href="#!" data-id="" data-bs-toggle="modal" data-bs-target="#addUserModal"   class="btn btn-success btn-sm" >Add User</a>
       </div>
       <div class="row">
        <div class="col-md-2"></div>
        <div class="col-md-8">
         <table id="example" class="table">
          <thead>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Mobile</th>
            <th>City</th>
            <th>Options</th>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>
      <div class="col-md-2"></div>
    </div>
  </div>
</div>
<?php include('modal.php'); ?>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $('#example').DataTable({
        "fnCreatedRow": function( nRow, aData, iDataIndex ) {
          $(nRow).attr('id', aData[0]);
        },
        'serverSide':'true',
        'processing':'true',
        'paging':'true',
        'order':[],
        'ajax': {
          'url':'fetch_data.php',
          'type':'post',
        },
        "columnDefs": [{
          'target':[5],
          'orderable' :false,
        }]
      });
    } );
    $(document).on('submit','#addUser',function(e){
      e.preventDefault();
      var city= $('#addCityField').val();
      var username= $('#addUserField').val();
      var mobile= $('#addMobileField').val();
      var email= $('#addEmailField').val();
      if(city != '' && username != '' && mobile != '' && email != '' )
      {
       $.ajax({
         url:"add_user.php",
         type:"post",
         data:{city:city,username:username,mobile:mobile,email:email},
         success:function(data)
         {
           var json = JSON.parse(data);
           var status = json.status;
           if(status=='true')
           {
            mytable =$('#example').DataTable();
            mytable.draw();
            $('#addUserModal').modal('hide');
          }
          else
          {
            alert('failed');
          }
        }
      });
     }
     else {
      alert('Fill all the required fields');
    }
  });
    $(document).on('submit','#updateUser',function(e){
      e.preventDefault();
       var city= $('#cityField').val();
       var username= $('#nameField').val();
       var mobile= $('#mobileField').val();
       var email= $('#emailField').val();
       var trid= $('#trid').val();
       var id= $('#id').val();
       if(city != '' && username != '' && mobile != '' && email != '' )
       {
         $.ajax({
           url:"update_user.php",
           type:"post",
           data:{city:city,username:username,mobile:mobile,email:email,id:id},
           success:function(data)
           {
             var json = JSON.parse(data);
             var status = json.status;
             if(status=='true')
             {
              table =$('#example').DataTable();
              var button =   '<td><a href="javascript:void();" data-id="' +id + '" class="btn btn-info btn-sm editbtn">Edit</a>  <a href="#!"  data-id="' +id + '"  class="btn btn-danger btn-sm deleteBtn">Delete</a></td>';
              var row = table.row("[id='"+trid+"']");
              row.row("[id='" + trid + "']").data([id,username,email,mobile,city,button]);
              $('#exampleModal').modal('hide');
            }
            else
            {
              alert('failed');
            }
          }
        });
       }
       else {
        alert('Fill all the required fields');
      }
    });
    $('#example').on('click','.editbtn ',function(event){
      var table = $('#example').DataTable();
      var trid = $(this).closest('tr').attr('id');
     var id = $(this).data('id');
     $('#exampleModal').modal('show');

     $.ajax({
      url:"get_single_data.php",
      data:{id:id},
      type:'post',
      success:function(data)
      {
       var json = JSON.parse(data);
       $('#nameField').val(json.username);
       $('#emailField').val(json.email);
       $('#mobileField').val(json.mobile);
       $('#cityField').val(json.city);
       $('#id').val(id);
       $('#trid').val(trid);
     }
   })
   });

    $(document).on('click','.deleteBtn',function(event){
       var table = $('#example').DataTable();
      event.preventDefault();
      var id = $(this).data('id');
      if(confirm("Are you sure want to delete this User ? "))
      {
      $.ajax({
        url:"delete_user.php",
        data:{id:id},
        type:"post",
        success:function(data)
        {
          var json = JSON.parse(data);
          status = json.status;
          if(status=='success')
          {
             $("#"+id).closest('tr').remove();
          }
          else
          {
            alert('Failed');
            return;
          }
        }
      });
      }
      else
      {
        return null;
      }
    })
 </script>
</body>
</html>
modal.php
//modal.php
<!-- Add user Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="addUser" action="">
          <div class="mb-3 row">
            <label for="addUserField" class="col-md-3 form-label">Name</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="addUserField" name="name" >
            </div>
          </div>
          <div class="mb-3 row">
            <label for="addEmailField" class="col-md-3 form-label">Email</label>
            <div class="col-md-9">
              <input type="email" class="form-control" id="addEmailField" name="email">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="addMobileField" class="col-md-3 form-label">Mobile</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="addMobileField" name="mobile">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="addCityField" class="col-md-3 form-label">City</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="addCityField" name="City">
            </div>
          </div>
          <div class="text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form> 
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
 <!-- Modal -->
 <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Update User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="updateUser" >
          <input type="hidden" name="id" id="id" value="">
          <input type="hidden" name="trid" id="trid" value="">
          <div class="mb-3 row">
            <label for="nameField" class="col-md-3 form-label">Name</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="nameField" name="name" >
            </div>
          </div>
          <div class="mb-3 row">
            <label for="emailField" class="col-md-3 form-label">Email</label>
            <div class="col-md-9">
              <input type="email" class="form-control" id="emailField" name="email">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="mobileField" class="col-md-3 form-label">Mobile</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="mobileField" name="mobile">
            </div>
          </div>
          <div class="mb-3 row">
            <label for="cityField" class="col-md-3 form-label">City</label>
            <div class="col-md-9">
              <input type="text" class="form-control" id="cityField" name="City">
            </div>
          </div>
          <div class="text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form> 
      </div>
      <div class="modal-footer">
        <button type="button"  class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
connection.php
//connection.php
<?php
$con  = mysqli_connect('localhost','root','','testingdb');
if(mysqli_connect_errno())
{
    echo 'Database Connection Error';
}
fetch_data.php
//fetch_data.php
<?php include('connection.php');

$output= array();
$sql = "SELECT * FROM users ";

$totalQuery = mysqli_query($con,$sql);
$total_all_rows = mysqli_num_rows($totalQuery);

if(isset($_POST['search']['value']))
{
	$search_value = $_POST['search']['value'];
	$sql .= " WHERE username like '%".$search_value."%'";
	$sql .= " OR email like '%".$search_value."%'";
	$sql .= " OR mobile like '%".$search_value."%'";
	$sql .= " OR city like '%".$search_value."%'";
}

if(isset($_POST['order']))
{
	$column_name = $_POST['order'][0]['column'];
	$order = $_POST['order'][0]['dir'];
	$sql .= " ORDER BY ".$column_name." ".$order."";
}
else
{
	$sql .= " ORDER BY id desc";
}

if($_POST['length'] != -1)
{
	$start = $_POST['start'];
	$length = $_POST['length'];
	$sql .= " LIMIT  ".$start.", ".$length;
}	

$query = mysqli_query($con,$sql);
$count_rows = mysqli_num_rows($query);
$data = array();
while($row = mysqli_fetch_assoc($query))
{
	$sub_array = array();
	$sub_array[] = $row['id'];
	$sub_array[] = $row['username'];
	$sub_array[] = $row['email'];
	$sub_array[] = $row['mobile'];
	$sub_array[] = $row['city'];
	$sub_array[] = '<a href="javascript:void();" data-id="'.$row['id'].'"  class="btn btn-info btn-sm editbtn" >Edit</a>  <a href="javascript:void();" data-id="'.$row['id'].'"  class="btn btn-danger btn-sm deleteBtn" >Delete</a>';
	$data[] = $sub_array;
}

$output = array(
	'draw'=> intval($_POST['draw']),
	'recordsTotal' =>$count_rows ,
	'recordsFiltered'=>   $total_all_rows,
	'data'=>$data,
);
echo  json_encode($output);
add_user.php
//add_user.php
<?php 
include('connection.php');
$username = $_POST['username'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$city = $_POST['city'];

$sql = "INSERT INTO `users` (`username`,`email`,`mobile`,`city`) values ('$username', '$email', '$mobile', '$city' )";
$query= mysqli_query($con,$sql);
$lastId = mysqli_insert_id($con);
if($query ==true)
{
    $data = array(
        'status'=>'true',
    );
    echo json_encode($data);
}
else
{
     $data = array(
        'status'=>'false',
    );
    echo json_encode($data);
} 
?>
get_single_data.php
//get_single_data.php
<?php include('connection.php');
$id = $_POST['id'];
$sql = "SELECT * FROM users WHERE id='$id' LIMIT 1";
$query = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($query);
echo json_encode($row);
?>
update_user.php
//update_user.php
<?php 
include('connection.php');
$username = $_POST['username'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$city = $_POST['city'];
$id = $_POST['id'];

$sql = "UPDATE `users` SET  `username`='$username' , `email`= '$email', `mobile`='$mobile',  `city`='$city' WHERE id='$id' ";
$query= mysqli_query($con,$sql);
$lastId = mysqli_insert_id($con);
if($query ==true)
{
   
    $data = array(
        'status'=>'true',
    );

    echo json_encode($data);
}
else
{
     $data = array(
        'status'=>'false',
    );
    echo json_encode($data);
} 
?>
delete_user.php
//delete_user.php
<?php 
include('connection.php');
$user_id = $_POST['id'];
$sql = "DELETE FROM users WHERE id='$user_id'";
$delQuery =mysqli_query($con,$sql);
if($delQuery==true)
{
	 $data = array(
        'status'=>'success',
    );
    echo json_encode($data);
}
else
{
     $data = array(
        'status'=>'failed',
    );
    echo json_encode($data);
} 
?>

Related Post