article

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

Saturday, July 23, 2022

PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)

PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)

https://github.com/benfoster/FitFrame.js
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

https://datatables.net/

database table 

CREATE TABLE `tblusers` (
  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
index.php
//index.php
<?php
   
  // Include database file
  include 'users.php';
 
  $userObj = new Users();
 
  // Delete record
  if(isset($_GET['deleteId']) && !empty($_GET['deleteId'])) {
      $deleteId = $_GET['deleteId'];
      $userObj->deleteRecord($deleteId);
  }
      
?> 
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
  <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css"/>
</head>
<body>
 
<div class="card text-center" style="padding:15px;">
  <h4>PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)</h4>
</div><br><br> 
 
<div class="container">
  <?php
    if (isset($_GET['msg1']) == "insert") {
      echo "<div class='alert alert-success alert-dismissible'>
              Your Registration added successfully
            </div>";
      } 
    if (isset($_GET['msg2']) == "update") {
      echo "<div class='alert alert-success alert-dismissible'>
              Your Registration updated successfully
            </div>";
    }
    if (isset($_GET['msg3']) == "delete") {
      echo "<div class='alert alert-success alert-dismissible'>
              Record deleted successfully
            </div>";
    }
  ?>
  <h2>View Records
    <a href="add.php" class="btn btn-primary" style="float:right;">Add New Record</a>
  </h2>
  <table class="table table-bordered table-striped" id="usersTable">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Username</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
        <?php 
          $users = $userObj->displayData(); 
          foreach ($users as $rs) {
        ?>
        <tr>
          <td><?php echo $rs['id'] ?></td>
          <td><?php echo $rs['name'] ?></td>
          <td><?php echo $rs['email'] ?></td>
          <td><?php echo $rs['username'] ?></td>
          <td>
            <a href="edit.php?editId=<?php echo $rs['id'] ?>" style="color:green">
              <i class="fa fa-pencil" aria-hidden="true"></i></a> 
            <a href="index.php?deleteId=<?php echo $rs['id'] ?>" style="color:red" onclick="confirm('Are you sure want to delete this record')">
              <i class="fa fa-trash" aria-hidden="true"></i>
            </a>
          </td>
        </tr>
      <?php } ?>
    </tbody>
  </table>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready( function () {
    $('#usersTable').DataTable();
} );
</script>
</body>
</html>
users.php
//users.php
<?php
 
    class Users
    {
        private $servername = "localhost";
        private $username   = "root";
        private $password   = "";
        private $database   = "projectdb";
        public  $con;
 
 
        // Database Connection 
        public function __construct()
        {
            $this->con = new mysqli($this->servername, $this->username,$this->password,$this->database);
            if(mysqli_connect_error()) {
				trigger_error("Failed to connect to MySQL: " . mysqli_connect_error());
            }else{
				return $this->con;
            }
        }
 
        // Insert data into table
        public function insertData($post)
        {
            $name = $this->con->real_escape_string($_POST['name']);
            $email = $this->con->real_escape_string($_POST['email']);
            $username = $this->con->real_escape_string($_POST['username']);
            $password = $this->con->real_escape_string(md5($_POST['password']));
            $query="INSERT INTO tblusers(name,email,username,password) VALUES('$name','$email','$username','$password')";
            $sql = $this->con->query($query);
            if ($sql==true) {
                header("Location:index.php?msg1=insert");
            }else{
                echo "Registration failed try again!";
            }
        }
 
        // Fetch all records
        public function displayData()
        {
            $query = "SELECT * FROM tblusers";
            $result = $this->con->query($query);
			if ($result->num_rows > 0) {
				$data = array();
				while ($row = $result->fetch_assoc()) {
					   $data[] = $row;
				}
				return $data;
            }else{
				echo "No found records";
            }
        }
 
        // Fetch single data
        public function displyaRecordById($id)
        {
            $query = "SELECT * FROM tblusers WHERE id = '$id'";
            $result = $this->con->query($query);
			if ($result->num_rows > 0) {
				$row = $result->fetch_assoc();
				return $row;
            }else{
				echo "Record not found";
            }
        }
 
        // Update data
        public function updateRecord($postData)
        {
            $name = $this->con->real_escape_string($_POST['uname']);
            $email = $this->con->real_escape_string($_POST['uemail']);
            $username = $this->con->real_escape_string($_POST['upname']);
            $id = $this->con->real_escape_string($_POST['id']);
			if (!empty($id) && !empty($postData)) {
				$query = "UPDATE tblusers SET name = '$name', email = '$email', username = '$username' WHERE id = '$id'";
				$sql = $this->con->query($query);
				if ($sql==true) {
					header("Location:index.php?msg2=update");
				}else{
					echo "Registration updated failed try again!";
				}
            }
             
        }
 
 
        // Delete data
        public function deleteRecord($id)
        {
            $query = "DELETE FROM tblusers WHERE id = '$id'";
            $sql = $this->con->query($query);
			if ($sql==true) {
				header("Location:index.php?msg3=delete");
			}else{
				echo "Record does not delete try again";
			}
		}
    }
?>
add.php
//add.php
<?php
 
  // Include database file
  include 'users.php';
 
  $userObj = new Users();
 
  // Insert Record 
  if(isset($_POST['submit'])) {
    $userObj->insertData($_POST);
  }
 
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
</head>
<body>
 
<div class="card text-center" style="padding:15px;">
  <h4>PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)</h4>
</div><br> 
 
<div class="container">
  <form action="add.php" method="POST">
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" name="name" placeholder="Enter name" required="">
    </div>
    <div class="form-group">
      <label for="email">Email address:</label>
      <input type="email" class="form-control" name="email" placeholder="Enter email" required="">
    </div>
    <div class="form-group">
      <label for="username">Username:</label>
      <input type="text" class="form-control" name="username" placeholder="Enter username" required="">
    </div>
    <div class="form-group">
      <label for="password">Password:</label>
      <input type="password" class="form-control" name="password" placeholder="Enter password" required="">
    </div>
    <input type="submit" name="submit" class="btn btn-primary" style="float:right;" value="Submit">
  </form>
</div>
</body>
</html>
edit.php
//edit.php
<?php
   
  // Include database file
  include 'users.php';
 
  $userObj = new Users();
 
  // Edit record
  if(isset($_GET['editId']) && !empty($_GET['editId'])) {
    $editId = $_GET['editId'];
    $rs = $userObj->displyaRecordById($editId);
  }
 
  // Update Record
  if(isset($_POST['update'])) {
    $userObj->updateRecord($_POST);
  }  
     
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
</head>
<body>
 
<div class="card text-center" style="padding:15px;">
  <h4>PHP Mysqli OOP CRUD (Add, Edit, Delete, View) OOP (Object Oriented Programming)</h4>
</div><br> 
 
<div class="container">
  <form action="edit.php" method="POST">
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" name="uname" value="<?php echo $rs['name']; ?>" required="">
    </div>
    <div class="form-group">
      <label for="email">Email address:</label>
      <input type="email" class="form-control" name="uemail" value="<?php echo $rs['email']; ?>" required="">
    </div>
    <div class="form-group">
      <label for="username">Username:</label>
      <input type="text" class="form-control" name="upname" value="<?php echo $rs['username']; ?>" required="">
    </div>
    <div class="form-group">
      <input type="hidden" name="id" value="<?php echo $rs['id']; ?>">
      <input type="submit" name="update" class="btn btn-primary" style="float:right;" value="Update">
    </div>
  </form>
</div>
</body>
</html>

Saturday, July 16, 2022

PHP Mysqli Populate Dropdown using JavaScript AJAX

PHP Mysqli Populate Dropdown using JavaScript 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

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

INSERT INTO `countries` (`id`, `name`) VALUES
(1, 'Afghanistan'),
(171, 'Philippines'),
(227, 'United States of America');

CREATE TABLE `states` (
  `id` int(11) NOT NULL,
  `name` varchar(80) NOT NULL,
  `country_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `states` (`id`, `name`, `country_id`) VALUES
(1, 'Manila', 171),
(2, 'Zambales', 171),
(3, 'Pampanga', 171),
(4, 'Bulacan', 171),
(9, 'Colorado', 227),
(10, 'California', 227),
(11, 'Arizona', 227),
(12, 'Alaska', 227),
(13, 'Alabama', 227);

CREATE TABLE `cities` (
  `id` int(11) NOT NULL,
  `name` varchar(80) NOT NULL,
  `state_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `cities` (`id`, `name`, `state_id`) VALUES
(1, 'Manila', 1),
(2, 'Pasay', 1),
(3, 'Quezon City', 1),
(4, 'Olongapo City', 2),
(5, 'Angeles City', 3),
(6, 'Malolos', 4),
(7, 'Denver', 9),
(8, 'Los Angeles', 10),
(9, 'Phoenix', 11),
(10, 'Anchorage', 12),
(11, 'Huntsville', 13);

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>PHP Mysqli Populate Dropdown using JavaScript AJAX</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container"><br/><br/>
    <div class="row">
        <div class="col-lg-10">
            <h2>PHP Mysqli Populate Dropdown using JavaScript AJAX</h2>
        </div>
    </div>
	<div class="row">
	<?php
	include "config.php";
	$sql = "SELECT * from countries order by name";
    $stmt = $con->prepare($sql); 
    $stmt->execute();
    $result = $stmt->get_result();

	?>
	<div class="row mb-3">
        <label class="col-sm-2 col-form-label">Country:</label>
		<div class="col-sm-10">
			<select id="country" onchange="getStates(this.value);" class="form-select">
	            <option value="0" >– Select Country –</option>
	            <?php
	            while ($row = $result->fetch_assoc() ){

	               $id = $row['id'];
	               $name = $row['name'];

	               echo "<option value='".$id."' >".$name."</option>";
	            }
	            ?>
			</select>
		</div>
    </div>
		
	<div class="row mb-3">
        <label class="col-sm-2 col-form-label">State:</label>
		<div class="col-sm-10">
	         <select id="state" onchange="getCities(this.value);" class="form-select">
	            <option value="0" >– Select State –</option>
	         </select>
		</div>
    </div>

	<div class="row mb-3">
        <label class="col-sm-2 col-form-label">City:</label>
		<div class="col-sm-10">
	         <select id="city" class="form-select">
	            <option value="0" >– Select City –</option>
	         </select>
		</div>
    </div>
	
	</div>
</div>	
<script type="text/javascript">
		function getStates(country_id){
			
			// Empty the dropdown
			var stateel = document.getElementById('state');
			var cityel = document.getElementById('city');
			
			stateel.innerHTML = "";
			cityel.innerHTML = "";

			var stateopt = document.createElement('option');
			stateopt.value = 0;
			stateopt.innerHTML = '-- Select State --';
			stateel.appendChild(stateopt);

			var cityopt = document.createElement('option');
			cityopt.value = 0;
			cityopt.innerHTML = '-- Select City --';
			cityel.appendChild(cityopt);

		    // AJAX request
		    var xhttp = new XMLHttpRequest();
			xhttp.open("POST", "ajaxfile.php", true); 
			xhttp.setRequestHeader("Content-Type", "application/json");
			xhttp.onreadystatechange = function() {
			   	if (this.readyState == 4 && this.status == 200) {
			     	// Response
			     	var response = JSON.parse(this.responseText);
			     	
			     	var len = 0;
		            if(response != null){
		               len = response.length;
		            }
		           
		            if(len > 0){
		               	// Read data and create <option >
		               	for(var i=0; i<len; i++){

		                  	var id = response[i].id;
		                  	var name = response[i].name;

		                  	// Add option to state dropdown
		                  	var opt = document.createElement('option');
						    opt.value = id;
						    opt.innerHTML = name;
						    stateel.appendChild(opt);

		               	}
		            }
			   	}
			};
			var data = {request:'getStates',country_id: country_id};
			xhttp.send(JSON.stringify(data));
		    
		}

		function getCities(state_id){

			// Empty the dropdown
			var cityel = document.getElementById('city');
			
			cityel.innerHTML = "";

			var cityopt = document.createElement('option');
			cityopt.value = 0;
			cityopt.innerHTML = '-- Select City --';
			cityel.appendChild(cityopt);

		    // AJAX request
		    var xhttp = new XMLHttpRequest();
			xhttp.open("POST", "ajaxfile.php", true); 
			xhttp.setRequestHeader("Content-Type", "application/json");
			xhttp.onreadystatechange = function() {
			   	if (this.readyState == 4 && this.status == 200) {
			     	// Response
			     	var response = JSON.parse(this.responseText);
			     	
			     	var len = 0;
		            if(response != null){
		               len = response.length;
		            }
		           
		            if(len > 0){
		               	// Read data and create <option >
		               	for(var i=0; i<len; i++){

		                  	var id = response[i].id;
		                  	var name = response[i].name;

		                  	// Add option to city dropdown
		                  	var opt = document.createElement('option');
						    opt.value = id;
						    opt.innerHTML = name;
						    cityel.appendChild(opt);

		               	}
		            }
			   	}
			};
			var data = {request:'getCities',state_id: state_id};
			xhttp.send(JSON.stringify(data));
		}
</script>
</body>
</html>
config.php
//config.php
<?php

$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "projectdb"; 

// Create connection
$con = new mysqli($host, $user, $password, $dbname);

// Check connection
if ($con->connect_error) {
  die("Connection failed: " . $con->connect_error);
}
ajaxfile.php
//ajaxfile.php
<?php
include 'config.php';

// Read POST data
$postData = json_decode(file_get_contents("php://input"));
$request = "";
if(isset($postData->request)){
   $request = $postData->request;
}

// Get states
if($request == 'getStates'){
   $country_id = 0;
   $result = array();$data = array();

   if(isset($postData->country_id)){
      $country_id = $postData->country_id;

      $sql = "SELECT * from states WHERE country_id=?";
      $stmt = $con->prepare($sql); 
      $stmt->bind_param("i", $country_id);
      $stmt->execute();
      $result = $stmt->get_result();

      while ($row = $result->fetch_assoc()){

         $id = $row['id'];
         $name = $row['name'];

         $data[] = array(
            "id" => $id,
            "name" => $name
         );

      }

   }

   echo json_encode($data);
   die;

}

// Get cities
if($request == 'getCities'){
   $state_id = 0;
   $result = array();$data = array();

   if(isset($postData->state_id)){
      $state_id = $postData->state_id;

      $sql = "SELECT * from cities WHERE state_id=?";
      $stmt = $con->prepare($sql); 
      $stmt->bind_param("i", $state_id);
      $stmt->execute();
      $result = $stmt->get_result();

      while ($row = $result->fetch_assoc()){

         $id = $row['id'];
         $name = $row['name'];

         $data[] = array(
            "id" => $id,
            "name" => $name
         );

      }
   }

   echo json_encode($data);
   die;
}

Tuesday, July 12, 2022

PHP Mysqli Highlight Deleted Row using Jquery AJAX

PHP Mysqli Highlight Deleted Row using 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

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
https://icons.getbootstrap.com/#install

https://datatables.net/

CREATE TABLE `users` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Mysqli Highlight Deleted Row using Jquery AJAX</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" 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.3/font/bootstrap-icons.css">
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" />
  <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container">
	<div class="row">
		<h4>PHP Mysqli Highlight Deleted Row using Jquery AJAX</h4>
		<div class="col-sm-10">
		<table class="table table-striped table-bordered" id="user_datatable"> 
			<thead>
			<tr>
				<th>Id</th>
				<th>Name</th>
				<th>Email</th>
				<th>Action</th>
			</tr>
			</thead>
			<tbody>
			<?php
				$conn = mysqli_connect('localhost','root','','projectdb');
	 
				$sql_select = "SELECT * FROM users";
				 
				$sel_query =  mysqli_query($conn,$sql_select);
				 
				while($row = mysqli_fetch_array($sel_query))
				{
					echo'<tr id="'.$row['id'].'">';
					 echo'<td>'.$row['id'].'</td>';
					 echo'<td>'.$row['name'].'</td>';
					 echo'<td>'.$row['email'].'</td>';
					 echo'<td> <button  class="remove" name="remove" id="'.$row['id'].'"><i class="bi bi-backspace-reverse-fill" style="color:red;"></i></button></td>';
					echo'</tr>';
				}
				?>
				 
			</tbody>
		</table>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
    
	$('#user_datatable').DataTable();
	
    $('.remove').click(function(){
  
        var userID = $(this).attr('id');
          alert(userID)
         
            $.ajax({
            type: "POST",
            url: "delete.php",
            data: {deleteID:userID},
            success: function(data)
                {
                    if(confirm('Are you sure you want to delete this?'))
                    {
                       
                       $('#' + userID).css("background-color", "palegreen");
                        setTimeout(function() {
                          $('#' + userID).remove();
                        },500);
                    }   
                }
            });
        // }
       });
});
</script> 
</body>
</html>
delete.php
//delete.php
<?php
    $conn = mysqli_connect('localhost','root','','projectdb');
 
    $deleteID = $_POST['deleteID'];
 
    $sql_select = "DELETE FROM users WHERE id = $deleteID";
    $sel_query =  mysqli_query($conn,$sql_select);
     
    if($sel_query)
    {
        echo "Success";
    }
    else
    {
        echo "Error";
    }
?>

Wednesday, July 6, 2022

PHP Mysqli Login and Sign Up using jQuery Ajax

PHP Mysqli Login and Sign Up using 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

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 `user` (
  `userid` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user` (`userid`, `username`, `password`) VALUES
(1, 'cairocoders', '25f9e794323b453885f5181f1b624d0b');

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

ALTER TABLE `user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.php
//index.php
<?php
	session_start();
	if(isset($_SESSION['user'])){
		header('location:home.php');
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login and Sign Up using jQuery Ajax</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>
	<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"/>
</head>
<body>
<p><center><h1>PHP Mysqli Login and Sign Up using jQuery Ajax </h1></center></p>
<div class="container">
	<div class="row">
		<div id="myalert" style="display:none;">
			<div class="alert alert-info">
				<center><span id="alerttext"></span></center>
			</div>
		</div>
    </div>
	
	<div class="row loginreg" id="loginform">
		<p><h1><i class="fa fa-lock" aria-hidden="true"></i> Login</h1></p>
		<form role="form" id="logform">
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fas fa-user-tie"></i></span>
				<input class="form-control" placeholder="Username" name="username" id="username" type="text" autofocus>
			</div>
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fa fa-key icon"></i></span>
				<input class="form-control" placeholder="Password" name="password" id="password" type="password">
			</div>
			<div class="checkbox">
				  <label><input type="checkbox" value=""/> Remember me</label>
			</div><br />
			<div>
				<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block"><i class="fa fa-lock" aria-hidden="true"></i> <span id="logtext">Login</span></button>
			</div>
			
			<center><div style="border:1px solid black;height:1px;width:300px;margin-top:20px;"></div></center>
			 
			<div class="footer">
				<p>Don't have an Account! <a href="#" id="signup">Sign Up Here</a></p>
				<p>Forgot <a href="#">Password?</a></p>
			</div>
		</form>
	</div>	
	
	<div class="row loginreg" id="signupform" style="display:none;">
		<p><h1><i class="fas fa-user-tie"></i> Sign Up</h1></p>
		<form role="form" id="signform">
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fas fa-user-tie"></i></span>
				<input class="form-control" placeholder="Username" name="susername" id="susername" type="text" autofocus>
			</div>
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fa fa-key icon"></i></span>
				<input class="form-control" placeholder="Password" name="spassword" id="spassword" type="password">
			</div>
			<div>
				<button type="button" id="signupbutton" class="btn btn-lg btn-info btn-block"><i class="fa fa-lock" aria-hidden="true"></i> <span id="signtext">Sign Up</span></button>
			</div>
			
			<center><div style="border:1px solid black;height:1px;width:300px;margin-top:20px;"></div></center>
			 
			<div class="footer">
				<p>have an Account! <a href="#" id="login">Login</a></p>
				<p>Forgot <a href="#">Password?</a></p>
			</div>
		</form>
	</div>
</div>
<script src="custom.js"></script>
<style>
  .container{
        border:2px solid blue;
        text-align:center;
        
        height:500px;
        width:400px;
    }
    body{
        padding:70px;
    }
    .loginreg {
        height:90px;
        width:396px;
        background-color:paleturquoise;
    }
	.row p { 
		padding-top:10px;
	}
</style>	
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "projectdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
login.php
//login.php
<?php 
	include('conn.php');
	session_start();
	if(isset($_POST['username'])){
		$username=$_POST['username'];
		$password=md5($_POST['password']);

		$query=$conn->query("select * from user where username='$username' and password='$password'");

		if ($query->num_rows>0){
			$row=$query->fetch_array();
			$_SESSION['user']=$row['userid']; 
		}
		else{
			?>
  				<span>Login Failed. User not Found.</span>
  			<?php 
		}
	}
?>
signup.php
//signup.php
<?php
	include('conn.php');
	if(isset($_POST['susername'])){
		$username=$_POST['susername'];
		$password=$_POST['spassword'];

		$query=$conn->query("select * from user where username='$username'");

		if ($query->num_rows>0){
			?>
  				<span>Username already exist.</span>
  			<?php 
		}

		elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$username)){
			?>
  				<span style="font-size:11px;">Invalid username. Space & Special Characters not allowed.</span>
  			<?php 
		}
		elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$password)){
			?>
  				<span style="font-size:11px;">Invalid password. Space & Special Characters not allowed.</span>
  			<?php 
		}
		else{
			$mpassword=md5($password);
			$conn->query("insert into user (username, password) values ('$username', '$mpassword')");
			?>
  				<span>Sign up Successful.</span>
  			<?php 
		}
	}
?>
session.php
//session.php
<?php
	session_start();
	include('conn.php');

	$query=$conn->query("select * from user where userid='".$_SESSION['user']."'");
	$row=$query->fetch_array();

	$user=$row['username'];
?>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	header('location:index.php');
?>
home.php
//home.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login and Sign Up using jQuery Ajax</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<div style="height:50px;">
	</div>
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
           <h2>Welcome, <?php echo $user; ?>!</h2>
           <a href="logout.php" class="btn btn-danger"> Logout</a>
        </div>
    </div>
</div>
</body>
</html>
script.js
//script.js
$(document).ready(function(){
	//bind enter key to click button
	$(document).keypress(function(e){
    	if (e.which == 13){
    		if($('#loginform').is(":visible")){
    			$("#loginbutton").click();
    		}
        	else if($('#signupform').is(":visible")){
        		$("#signupbutton").click();
        	}
    	}
	});

	$('#signup').click(function(event){
		event.preventDefault();
		$('#loginform').slideUp();
		$('#signupform').slideDown();
		$('#myalert').slideUp();
		$('#signform')[0].reset();
	});

	$('#login').click(function(event){
		event.preventDefault();
		$('#loginform').slideDown();
		$('#signupform').slideUp();
		$('#myalert').slideUp();
		$('#logform')[0].reset();
	});

	$(document).on('click', '#signupbutton', function(){
		if($('#susername').val()!='' && $('#spassword').val()!=''){
			$('#signtext').text('Signing up...');
			$('#myalert').slideUp();
			var signform = $('#signform').serialize();
			$.ajax({
				method: 'POST',
				url: 'signup.php',
				data: signform,
				success:function(data){
					setTimeout(function(){
					$('#myalert').slideDown();
					$('#alerttext').html(data);
					$('#signtext').text('Sign up');
					$('#signform')[0].reset();
					}, 2000);
				} 
			});
		}
		else{
			alert('Please input both fields to Sign Up');
		}
	});

	$(document).on('click', '#loginbutton', function(){
		if($('#username').val()!='' && $('#password').val()!=''){
			$('#logtext').text('Logging in...');
			$('#myalert').slideUp();
			var logform = $('#logform').serialize();
			setTimeout(function(){
				$.ajax({
					method: 'POST',
					url: 'login.php',
					data: logform,
					success:function(data){
						if(data==''){
							$('#myalert').slideDown();
							$('#alerttext').text('Login Successful. User Verified!');
							$('#logtext').text('Login');
							$('#logform')[0].reset();
							setTimeout(function(){
								location.reload();
							}, 2000);
						}
						else{
							$('#myalert').slideDown();
							$('#alerttext').html(data);
							$('#logtext').text('Login');
							$('#logform')[0].reset();
						}
					} 
				});
			}, 2000);
		}
		else{
			alert('Please input both fields to Login');
		}
	});
});

Friday, July 1, 2022

PHP PDO CRUD (Create Read Update and Delete) with Bootstrap 5 Modal

PHP PDO CRUD (Create Read Update and Delete) 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
 
CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Cairo', 'Ednalan', 'Olongapo City'),
(2, 'clydey', 'Ednalan', 'Olongapo City'),
(3, 'Airi ', 'Satou', 'Tokyo'),
(4, 'Ashton ', 'Cox', 'San Francisco');


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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>PHP PDO CRUD (Create Read Update and Delete) with Bootstrap 5 Modall</title>
	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">PHP PDO CRUD (Create Read Update and Delete) with Bootstrap 5 Modal</h1>
	<div class="row">
		<div class="col-12">
			<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnew">
			  Add New
			</button>
            <?php 
                session_start();
                if(isset($_SESSION['message'])){
                    ?>
                    <div class="alert alert-info text-center" style="margin-top:20px;">
                        <?php echo $_SESSION['message']; ?>
                    </div>
                    <?php

                    unset($_SESSION['message']);
                }
            ?>
			<table class="table table-bordered table-striped" style="margin-top:20px;">
				<thead>
					<th>ID</th>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Address</th>
					<th>Action</th>
				</thead>
				<tbody>
					<?php
						include_once('connection.php');

						$database = new Connection();
    					$db = $database->open();
						try{	
						    $sql = 'SELECT * FROM members';
						    foreach ($db->query($sql) as $row) {
						    	?>
						    	<tr>
						    		<td><?php echo $row['id']; ?></td>
						    		<td><?php echo $row['firstname']; ?></td>
						    		<td><?php echo $row['lastname']; ?></td>
						    		<td><?php echo $row['address']; ?></td>
						    		<td>
						    			<a href="#edit_<?php echo $row['id']; ?>" class="btn btn-success btn-sm" data-bs-toggle="modal"> Edit</a>
						    			<a href="#delete_<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" data-bs-toggle="modal"> Delete</a>
						    		</td>
						    		<?php include('edit_delete_modal.php'); ?>
						    	</tr>
						    	<?php 
						    }
						}
						catch(PDOException $e){
							echo "There is some problem in connection: " . $e->getMessage();
						}

						//close connection
						$database->close();

					?>
				</tbody>
			</table>
		</div>
	</div>
</div>
<?php include('add_modal.php'); ?>
<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.min.js"></script>
</body>
</html>
connection.php
//connection.php
<?php
Class Connection{
 
	private $server = "mysql:host=localhost;dbname=devprojectdb";
	private $username = "root";
	private $password = "";
	private $options  = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
	protected $conn;
 	
	public function open(){
 		try{
 			$this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
 			return $this->conn;
 		}
 		catch (PDOException $e){
 			echo "There is some problem in connection: " . $e->getMessage();
 		}
 
    }
 
	public function close(){
   		$this->conn = null;
 	}
 
}
?>
add_modal.php
//add_modal.php
<!-- Add New -->
<div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="ModalLabel">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="add.php">
			<div class="mb-3 row">
				<label class="col-sm-2 col-form-label">Firstname</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" name="firstname">
				</div>
			</div>
			<div class="mb-3 row">
				<label class="col-sm-2 col-form-label">Lastname</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" name="lastname">
				</div>
			</div>
			<div class="mb-3 row">
				<label class="col-sm-2 col-form-label">Address</label>
				<div class="col-sm-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" name="add" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
		</form>
      </div>
    </div>
  </div>
</div>
edit_delete_modal.php
//edit_delete_modal.php
<!-- Edit -->
<div class="modal fade" id="edit_<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="ModalLabel">Edit Membe</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
		<form method="POST" action="edit.php?id=<?php echo $row['id']; ?>">
			<div class="mb-3 row">
				<label class="col-sm-2 col-form-label">Firstname</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" name="firstname" value="<?php echo $row['firstname']; ?>">
				</div>
			</div>
			<div class="mb-3 row">
				<label class="col-sm-2 col-form-label">Lastname</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" name="lastname" value="<?php echo $row['lastname']; ?>">
				</div>
			</div>
			<div class="mb-3 row">
				<label class="col-sm-2 col-form-label">Address</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" name="address" value="<?php echo $row['address']; ?>">
				</div>
			</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
		<button type="submit" name="edit" class="btn btn-primary"> Update</a>
		</form>
      </div>
    </div>
  </div>
</div>

<!-- Delete -->
<div class="modal fade" id="delete_<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="ModalLabel">Delete Membe</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
            <p class="text-center">Are you sure you want to Delete</p>
			<h2 class="text-center"><?php echo $row['firstname'].' '.$row['lastname']; ?></h2>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
		<a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger"> Yes</a>
      </div>
    </div>
  </div>
</div>
add.php
//add.php
<?php
	session_start();
	include_once('connection.php');

	if(isset($_POST['add'])){
		$database = new Connection();
		$db = $database->open();
		try{
			//use prepared statement to prevent sql injection
			$stmt = $db->prepare("INSERT INTO members (firstname, lastname, address) VALUES (:firstname, :lastname, :address)");
			//if-else statement in executing our prepared statement
			$_SESSION['message'] = ( $stmt->execute(array(':firstname' => $_POST['firstname'] , ':lastname' => $_POST['lastname'] , ':address' => $_POST['address'])) ) ? 'Member added successfully' : 'Something went wrong. Cannot add member';	
	    
		}
		catch(PDOException $e){
			$_SESSION['message'] = $e->getMessage();
		}

		//close connection
		$database->close();
	}

	else{
		$_SESSION['message'] = 'Fill up add form first';
	}

	header('location: index.php');
	
?>
edit.php
//edit.php
<?php
	session_start();
	include_once('connection.php');

	if(isset($_POST['edit'])){
		$database = new Connection();
		$db = $database->open();
		try{
			$id = $_GET['id'];
			$firstname = $_POST['firstname'];
			$lastname = $_POST['lastname'];
			$address = $_POST['address'];

			$sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$id'";
			//if-else statement in executing our query
			$_SESSION['message'] = ( $db->exec($sql) ) ? 'Member updated successfully' : 'Something went wrong. Cannot update member';

		}
		catch(PDOException $e){
			$_SESSION['message'] = $e->getMessage();
		}

		//close connection
		$database->close();
	}
	else{
		$_SESSION['message'] = 'Fill up edit form first';
	}

	header('location: index.php');

?>
delete.php
//delete.php
<?php
	session_start();
	include_once('connection.php');

	if(isset($_GET['id'])){
		$database = new Connection();
		$db = $database->open();
		try{
			$sql = "DELETE FROM members WHERE id = '".$_GET['id']."'";
			//if-else statement in executing our query
			$_SESSION['message'] = ( $db->exec($sql) ) ? 'Member deleted successfully' : 'Something went wrong. Cannot delete member';
		}
		catch(PDOException $e){
			$_SESSION['message'] = $e->getMessage();
		}

		//close connection
		$database->close();

	}
	else{
		$_SESSION['message'] = 'Select member to delete first';
	}

	header('location: index.php');

?>

Monday, June 27, 2022

PHP MySQLi Upload Multiple Files

PHP MySQLi Upload Multiple Files

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

CREATE TABLE `photo` (
  `photoid` INT(11) NOT NULL AUTO_INCREMENT,
  `location` VARCHAR(150) NOT NULL,
PRIMARY KEY(`photoid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP MySQLi Upload Multiple Files</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
	<div class="row">
		<span style="font-size:25px; color:blue"><center><strong>PHP MySQLi Upload Multiple Files</strong></center></span>
		<hr> <br/>		
		<form method="POST" action="upload.php" enctype="multipart/form-data">
		<input class="form-control form-control-lg" id="formFileLg" type="file" name="upload[]" multiple>
		<br/>
		<input type="submit" value="Upload" class="btn btn-primary mb-3"> 
		</form>
	</div>
	<div class="row">
		<h2>Output:</h2>
		<?php
			include('conn.php');
			$query=mysqli_query($conn,"select * from photo");
			while($row=mysqli_fetch_array($query)){
				?>
				<div class="col-lg-3 col-md-4 col-6">
				  <a href="#" class="d-block mb-4 h-100">
					<img class="img-fluid img-thumbnail" src="<?php echo $row['location']; ?>" alt="">
				  </a>
				</div>
				<?php
			}
 
		?>
	</div>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","devprojectdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
upload.php
//upload.php
<?php
	include('conn.php');
 
	foreach ($_FILES['upload']['name'] as $key => $name){
 
		$newFilename = time() . "_" . $name;
		move_uploaded_file($_FILES['upload']['tmp_name'][$key], 'upload/' . $newFilename);
		$location = 'upload/' . $newFilename;
 
		mysqli_query($conn,"insert into photo (location) values ('$location')");
	}
	header('location:index.php');
?>

Sunday, June 26, 2022

PHP Mysqli Login with OOP (Object-Oriented Programming)

PHP Mysqli Login with OOP (Object-Oriented Programming)

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

Database Table 
CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(150) NOT NULL,
  `password` varchar(255) NOT NULL,
  `fullname` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `username`, `password`, `fullname`) VALUES
(1, 'cairocoders', '$2y$10$0qlCkQg4W97Sutj16Zg92uNssc2tAm6j2wIkiKvLlgMy2Td6dXGwC', 'Cairocoders Ednalan');

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

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.php
//index.php
<?php
	//start session
	session_start();
 
	//redirect if logged in
	if(isset($_SESSION['user'])){
		header('location:home.php');
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login with OOP (Object-Oriented Programming)</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<section class="body">
    <div class="container"><h1 class="page-header text-center">PHP Mysqli Login with OOP (Object-Oriented Programming)</h1>
        <div class="login-box">
            <div class="row">
                <div class="col-12">
                    <div class="logo">
                        Cairocoders
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <br>
                    <h3 class="header-title">Login</h3>
					<form class="login-form" method="POST" action="login.php">
                        <div class="form-group">
							<input class="form-control" placeholder="Username" type="text" name="username" autofocus required>
                        </div>
                        <div class="form-group">
							<input class="form-control" placeholder="Password" type="password" name="password" required>
                            <a href="#!" class="forgot-password">Forgot Password?</a>
                        </div>
                        <div class="form-group">
                            <button type="submit" name="login" class="btn btn-lg btn-primary btn-block">Login</button>
                        </div>
                        <div class="form-group">
                            <div class="text-center">New Member? <a href="#!">Sign up Now</a></div>
                        </div>
                    </form>
				<?php //$password = "123456";
					//echo password_hash($password, PASSWORD_DEFAULT);
					if(isset($_SESSION['message'])){
						?>
							<div class="alert alert-info text-center">
								<?php echo $_SESSION['message']; ?>
							</div>
						<?php
	 
						unset($_SESSION['message']);
					}
				?>
                </div>
                
            </div>
        </div>
    </div>
</section>
<style>
@import url(https://fonts.googleapis.com/css?family=Roboto:300,400,700&display=swap);

body {
    background: #f5f5f5;
}

.login-box {
    background-color:#fff; width:550px;
    background-position: center;
    padding: 50px;
    margin: 50px auto;
    min-height: 650px;
    -webkit-box-shadow: 0 2px 60px -5px rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 60px -5px rgba(0, 0, 0, 0.1);
}

.logo {
    font-family: "Script MT";
    font-size: 54px;
    text-align: center;
    color: #888888;
    margin-bottom: 50px;
}
.header-title {
    text-align: center;
    margin-bottom: 50px;
}
.login-form {
    max-width: 300px;
    margin: 0 auto;
}

.login-form .form-control {
    border-radius: 0;
    margin-bottom: 30px;
}

.login-form .form-group {
    position: relative;
}

.login-form .form-group .forgot-password {
    position: absolute;
    top: 6px;
    right: 15px;
}

.login-form .btn {
    border-radius: 0;
    -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    margin-bottom: 30px;
}

.login-form .btn.btn-primary {
    background: #3BC3FF;
    border-color: #31c0ff;
}
</style>
</body>
</html>
login.php
//login.php
<?php
//start session
session_start();
 
include_once('User.php');
 
$user = new User();
 
if(isset($_POST['login'])){
	$username = $user->escape_string($_POST['username']);
	$password = $user->escape_string($_POST['password']);
 
	$auth = $user->check_login($username, $password);

	if(!$auth){
		$_SESSION['message'] = 'Invalid username or password';
    	header('location:index.php');
	}
	else{
		$_SESSION['user'] = $auth;
		header('location:home.php');
	}
}
else{
	$_SESSION['message'] = 'You need to login first';
	header('location:index.php');
}
?>
User.php
//DbConnection.php
<?php
class DbConnection{
 
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'devprojectdb';
 
    protected $connection;
 
    public function __construct(){
 
        if (!isset($this->connection)) {
 
            $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
 
            if (!$this->connection) {
                echo 'Cannot connect to database server';
                exit;
            }            
        }    
 
        return $this->connection;
    }
}
?>
User.php
//User.php
<?php
include_once('DbConnection.php');
 
class User extends DbConnection{
 
    public function __construct(){
 
        parent::__construct();
    }
 
    public function check_login($username, $password){
 
        $sql = "SELECT * FROM users WHERE username = '$username'";
        $query = $this- >connection- >query($sql);
 
        if($query- >num_rows  > 0){
            $row = $query- >fetch_array();
			if(password_verify($password, $row['password'])){
				return $row['id'];
			}else {
				return false;
			}		
        }
        else{
            return false;
        }
    }
 
    public function details($sql){
 
        $query = $this- >connection- >query($sql);
 
        $row = $query- >fetch_array();
 
        return $row;       
    }
 
    public function escape_string($value){
 
        return $this- >connection- >real_escape_string($value);
    }
}
home.php
//home.php
<?php
session_start();
//return to login if not logged in
if (!isset($_SESSION['user']) ||(trim ($_SESSION['user']) == '')){
	header('location:index.php');
}
 
include_once('User.php');
 
$user = new User();
 
//fetch user data
$sql = "SELECT * FROM users WHERE id = '".$_SESSION['user']."'";
$row = $user->details($sql);
 
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Mysqli OOP Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">PHP Mysqli OOP Login</h1>
	<div class="row">
		<div class="col-md-4 col-md-offset-4">
			<h2>Welcome to Homepage </h2>
			<h4>User Info: </h4>
			<p>Name: <?php echo $row['fullname']; ?></p>
			<p>Username: <?php echo $row['username']; ?></p>
			<p>Password: <?php echo $row['password']; ?></p>
			<a href="logout.php" class="btn btn-danger"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
		</div>
	</div>
</div>
</body>
</html>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
 
	header('location:index.php');
?>

Friday, June 24, 2022

PHP MySQLi Delete Table Row using Sweetalert2

PHP MySQLi Delete Table Row using Sweetalert2

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

sweetalert2
https://sweetalert2.github.io/#download
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>How to Delete Table Row using Sweetalert2 with PHP/MySQLi</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>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
	
	<link href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>

	<style type="text/css">
		.mt20{
			margin-top:20px;
		}
	</style>
</head>
<body>
<div class="container">
	<h1 class="text-center mt20">PHP MySQLi Delete Table Row using Sweetalert2 </h1>
	<div class="row justify-content-center">
		<div class="col-sm-8">
			<table class="table table-bordered mt20">
				<thead>
					<th>ID</th>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Address</th>
					<th>Action</th>
				</thead>
				<tbody id="tbody">
				</tbody>
			</table>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	fetch();
 
	$(document).on('click', '.btn_delete', function(){
		var id = $(this).data('id');
 
		swal.fire({
		  	title: 'Are you sure?',
		  	text: "You won't be able to revert this!",
		  	icon: 'warning',
		  	showCancelButton: true,
		  	confirmButtonColor: '#3085d6',
		  	cancelButtonColor: '#d33',
		  	confirmButtonText: 'Yes, delete it!',
		}).then((result) => {
		  	if (result.value){
		  		$.ajax({
			   		url: 'ajaxfile.php?action=delete',
			    	type: 'POST',
			       	data: 'id='+id,
			       	dataType: 'json'
			    })
			    .done(function(response){
			     	swal.fire('Deleted!', response.message, response.status);
					fetch();
			    })
			    .fail(function(){
			     	swal.fire('Oops...', 'Something went wrong with ajax !', 'error');
			    });
		  	}
 
		})
 
	});
});
 
function fetch(){
	$.ajax({
		method: 'POST',
		url: 'ajaxfile.php',
		dataType: 'json',
		success: function(response){
			$('#tbody').html(response);
		}
	});
}
</script>
</body>
</html>

Sunday, June 19, 2022

PHP Mysqli Delete Multiple Rows using jQuery Ajax

PHP Mysqli Delete Multiple Rows using 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

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
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>PHP Mysqli Delete Multiple Rows using jQuery Ajax</title>
	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<h1 class="text-center" style="margin-top:30px;">PHP Mysqli Delete Multiple Rows using jQuery Ajax</h1>
	<hr>
	<div class="row justify-content-center">
		<div class="col-8">
			<div class="alert alert-danger text-center" role="alert" style="display:none;">
				<span class="message"></span>
			</div>
			<div class="alert alert-success text-center" role="alert" style="display:none;">
				<span class="message"></span>
			</div>
			<button type="button" class="btn btn-danger" id="delete">Delete</button>
			<table class="table table-bordered" style="margin-top:15px;">
				<thead>
					<th><input type="checkbox" id="checkAll"></th>
					<th>ID</th>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Address</th>
				</thead>
				<tbody id="tbody">
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
$(function(){
	fetch();

	//check uncheck all
	$('#checkAll').click(function () {
	    $('input:checkbox').not(this).prop('checked', this.checked);
	});

	$('#delete').click(function(){
		var ids = $(".check:checked").map(function(){
		  	return $(this).val();
		}).toArray();

		//check if a checkbox is checked
		if(jQuery.isEmptyObject(ids)){
			$('.alert').hide();
			$('.alert-danger').show();
			$('.message').html('Select row(s) to delete first');
		}
		//delete the checked rows
		else{
			$.ajax({
				type: 'POST',
				url: 'ajax.php?action=delete',
				data: {ids: ids},
				dataType: 'json',
				success: function(response){
					$('.alert').hide();
					$('.alert-success').show();
					$('.message').html(response);
					fetch();

				}
			});
		}

	});
	
});

function fetch(){
	$.ajax({
		type: 'POST',
		url: 'ajax.php',
		dataType: 'json',
		success: function(response){
			$('#tbody').html(response);
		}
	});
}
ajax.php
//ajax.php
<?php
	//connection
	$conn = new mysqli('localhost', 'root', '', 'devprojectdb');

	$action = 'fetch';
	$output = '';

	if(isset($_GET['action'])){
		$action = $_GET['action'];
	}

	if($action == 'fetch'){
		
		$sql = "SELECT * FROM members";
		$query = $conn->query($sql);

		while($row = $query->fetch_assoc()){
			$output .= "
				<tr>
					<td><input type='checkbox' class='check' value='".$row['id']."'></td>
					<td>".$row['id']."</td>
					<td>".$row['firstname']."</td>
					<td>".$row['lastname']."</td>
					<td>".$row['address']."</td>
				</tr>	
			";
		}

	}

	if($action == 'delete'){
		$output = array('error'=>false);
		$ids = $_POST['ids'];
		$count = count($ids);
		$row = ($count == 1)? 'Row' : 'Rows';

		foreach($ids as $id){
			$sql = "DELETE FROM members WHERE id = '$id'";
			$conn->query($sql);
		}
	
		$output = $count.' '.$row.' deleted';

	}

	echo json_encode($output);

?>

Saturday, June 18, 2022

PHP Mysqli CRUD (Create, Read, Update and Delete) using OOP

PHP Mysqli CRUD (Create, Read, Update and Delete) using OOP

Database Table 

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

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'clydety', 'Ednalan', 'Olongapo City'),
(2, 'Airi ', 'Satou', 'Tokyo'),
(13, 'Cairo', 'Ednalan', 'New Cabalan Olongapo City'),
(14, 'Angelica ', 'Ramos', 'London');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
  
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/

Database Connection

DbConnection.php
//DbConnection.php
<?php
class DbConnection 
{    
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'devprojectdb';
    
    protected $connection;
    
    public function __construct(){

        if (!isset($this->connection)) {
            
            $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
            
            if (!$this->connection) {
                echo 'Cannot connect to database server';
                exit;
            }            
        }    
        
        return $this->connection;
    }
}
?>
Database Action
Crud.php
//Crud.php
<?php
include_once('DbConnection.php');
 
class Crud extends DbConnection
{
    public function __construct(){

        parent::__construct();
    }
    
    public function read($sql){

        $query = $this->connection->query($sql);
        
        if ($query == false) {
            return false;
        } 
        
        $rows = array();
        
        while ($row = $query->fetch_array()) {
            $rows[] = $row;
        }
        
        return $rows;
    }
        
    public function execute($sql){

        $query = $this->connection->query($sql);
        
        if ($query == false) {
            return false;
        } else {
            return true;
        }        
    }
    
    public function escape_string($value){
        
        return $this->connection->real_escape_string($value);
    }
}
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>PHP Mysqli CRUD (Create, Read, Update and Delete) using OOP</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">PHP Mysqli CRUD (Create, Read, Update and Delete) using OOP</h1>
	<div class="row">
		<div class="col-12">
		<?php
			//start session
			session_start();

			include_once('Crud.php');

			$crud = new Crud();

			//fetch data
			$sql = "SELECT * FROM members";
			$result = $crud->read($sql);

			if(isset($_SESSION['message'])){
		?>
				<div class="alert alert-info text-center">
					<?php echo $_SESSION['message']; ?>
				</div>
			<?php
				unset($_SESSION['message']);
			} ?>
			<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#add">Add New</button>
			<br><br>
			<table class="table table-bordered table-striped">
				<thead>
					<tr>
						<th>ID</th>
						<th>Firstname</th>
						<th>Lastname</th>
						<th>Address</th>
						<th>Action</th>
					</tr>
				</thead>
				<tbody>
					<?php
						foreach ($result as $key => $row) {
							?>
							<tr>
								<td><?php echo $row['id']; ?></td>
								<td><?php echo $row['firstname']; ?></td>
								<td><?php echo $row['lastname']; ?></td>
								<td><?php echo $row['address']; ?></td>
								<td>
								<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#edit<?php echo $row['id']; ?>">Edit</button> | 
								<button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#delete<?php echo $row['id']; ?>">Delete</button>  
								</td>
								<?php include('action_modal.php'); ?>
							</tr>
							<?php     
					    }
					?>
				</tbody>
			</table>
		</div>
	</div>
</div>
<?php include('add_modal.php'); ?>
<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.min.js" rel="stylesheet"></script>
</body>
</html>
add_modal.php
//add_modal.php
<!-- Add New -->
<div class="modal fade" id="add" tabindex="-1" aria-labelledby="addlabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addlabel">Add Member</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
			<form method="POST" action="add.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" name="add" class="btn btn-primary">Save</button>
			</form>
      </div>
    </div>
  </div>
</div>
action_modal.php
//action_modal.php
<!-- Delete -->
<div class="modal fade" id="delete<?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="myModalLabel">Delete Member</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
			<h5>Are sure you want to delete</h5>
			<h2>Name: <b><?php echo $row['firstname'].' '.$row['lastname']; ?></b></h2> 
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
		<a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger">Yes</a>
      </div>
    </div>
  </div>
</div>

<!-- Edit -->
<div class="modal fade" id="edit<?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="myModalLabel">Edit Member</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
			<form method="POST" action="edit.php?id=<?php echo $row['id']; ?>">
				<div class="row">
					<div class="col-lg-2">
						<label style="position:relative; top:7px;">Firstname:</label>
					</div>
					<div class="col-lg-10">
						<input type="text" name="firstname" class="form-control" value="<?php echo $row['firstname']; ?>">
					</div>
				</div>
				<div style="height:10px;"></div>
				<div class="row">
					<div class="col-lg-2">
						<label style="position:relative; top:7px;">Lastname:</label>
					</div>
					<div class="col-lg-10">
						<input type="text" name="lastname" class="form-control" value="<?php echo $row['lastname']; ?>">
					</div>
				</div>
				<div style="height:10px;"></div>
				<div class="row">
					<div class="col-lg-2">
						<label style="position:relative; top:7px;">Address:</label>
					</div>
					<div class="col-lg-10">
						<input type="text" name="address" class="form-control" value="<?php echo $row['address']; ?>">
					</div>
				</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
		<button type="submit" name="edit" class="btn btn-warning">Save</button>
		</form>
      </div>
    </div>
  </div>
</div>
add.php
//add.php
<?php
//start session
session_start();

include_once('Crud.php');
 
$crud = new Crud();
 
if(isset($_POST['add'])) {    
    $firstname = $crud->escape_string($_POST['firstname']);
    $lastname = $crud->escape_string($_POST['lastname']);
    $address = $crud->escape_string($_POST['address']);
        
    $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname','$lastname','$address')";

    if($crud->execute($sql)){
        $_SESSION['message'] = 'Member added successfully';
    }
    else{
        $_SESSION['message'] = 'Cannot add member';
    }
        
    header('location: index.php');
}
else{
    $_SESSION['message'] = 'Fill up add form first';
    header('location: index.php');
}
?>
edit.php
//edit.php
<?php
//start session
session_start();

include_once('Crud.php');

$id = $_GET['id'];
 
$crud = new Crud();
 
if(isset($_POST['edit'])) {    
    $firstname = $crud->escape_string($_POST['firstname']);
    $lastname = $crud->escape_string($_POST['lastname']);
    $address = $crud->escape_string($_POST['address']);
        
    $sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$id'";

    if($crud->execute($sql)){
        $_SESSION['message'] = 'Member updated successfully';
    }
    else{
        $_SESSION['message'] = 'Cannot update member';
    }
        
    header('location: index.php');
}
else{
    $_SESSION['message'] = 'Select user to edit first';
    header('location: index.php');
}
?>
delete.php
//delete.php
<?php
//start session
session_start();

include_once('Crud.php');

if(isset($_GET['id'])){

    //get id
    $id = $_GET['id'];
     
    $crud = new Crud();

    $sql = "DELETE FROM members WHERE id = '$id'";

    if($crud->execute($sql)){
        $_SESSION['message'] = 'Member deleted successfully';
    }
    else{
        $_SESSION['message'] = 'Cannot delete member';
    }
        
    header('location: index.php');
}
else{
    $_SESSION['message'] = 'Select user to delete first';
    header('location: index.php');
}
?>

Tuesday, June 7, 2022

PHP Mysql PDO Image Upload and Insert with validation and preview

PHP Mysql PDO Image Upload and Insert with validation and preview

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

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

ALTER TABLE `user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
  
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
Database configuration

config.php
//config.php
<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";
 
    try {
        $conn = new PDO("mysql:host=$hostname;dbname=devprojectdb", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //echo "Database connected successfully";
    } catch(PDOException $e) {
        echo "Database connection failed: " . $e->getMessage();
    }
?>
Main Page
fileupload.php
//fileupload.php
<!doctype html>
<html lang="en">
<head>
    <title>PHP Mysql PDO Image Upload and Insert with validation and preview</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<?php include("save.php"); ?>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 offset-2">
                <div class="card">
                    <div class="card-header">
                        <h3 class="text-center">PHP Mysql PDO Image Upload and Insert with validation and preview</h3>
                    </div>
                    <div class="card-body">
                        <!-- response messages -->
                        <?php if(!empty($resMessage)) {?>
                            <div class="alert <?php echo $resMessage['status']?>">
                                <?php echo $resMessage['message']?>
                            </div>
                        <?php }?>
                        <form action="" method="post" enctype="multipart/form-data" class="mb-3">
                            <div class="user-image mb-3 text-center">
                                <div style="width: 100px; height: 100px; overflow: hidden; background: #cccccc; margin: 0 auto">
                                    <img src="..." class="figure-img img-fluid rounded" id="imgPlaceholder" alt="">
                                </div>
                            </div>
                            <div class="custom-file">
								<div class="input-group mb-3">
								  <input type="file" name="fileUpload" class="form-control" id="chooseFile">
								  <label class="input-group-text" for="chooseFile">Select file</label>
								</div>
                            </div>
                            <button type="submit" name="submit" class="btn btn-success">
                                Upload File
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#imgPlaceholder').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]); // convert to base64 string
            }
        }
        $("#chooseFile").change(function () {
            readURL(this);
        });
    </script>
</body>
</html>
file for storing the data
save.php
//save.php
<?php 
    // Database connection
    include("config.php");
     
    if(isset($_POST["submit"])) {
        // Set image placement folder
        $target_dir = "images/";
        // Get file path
        $target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);
        // Get file extension
        $imageExt = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        // Allowed file types
        $allowd_file_ext = array("jpg", "jpeg", "png");
 
        if (!file_exists($_FILES["fileUpload"]["tmp_name"])) {
           $resMessage = array(
               "status" => "alert-danger",
               "message" => "Select image to upload."
           );
        } else if (!in_array($imageExt, $allowd_file_ext)) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "Allowed file formats .jpg, .jpeg and .png."
            );            
        } else if ($_FILES["fileUpload"]["size"] > 2097152) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "File is too large. File size should be less than 2 megabytes."
            );
        } else if (file_exists($target_file)) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "The File already exists."
            );
        } else {
            if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {
                $sql = "INSERT INTO user (image) VALUES ('$target_file')";
                $stmt = $conn->prepare($sql);
                if($stmt->execute()){
                    $resMessage = array(
                        "status" => "alert-success",
                        "message" => "Image uploaded successfully."
                    );                 
                 }
            } else {
                $resMessage = array(
                    "status" => "alert-danger",
                    "message" => "Image can not be uploaded."
                );
            }
        }
    }
?>

Thursday, June 2, 2022

Login and Register using PDO PHP Mysql

Login and Register using PDO PHP Mysql

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

font-awesome
https://cdnjs.com/libraries/font-awesome

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `reg_date` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

Database Connection
conn.php
//conn.php
<?php
 
$host = 'localhost';
$db   = 'devprojectdb';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
 
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $options);
 
?>
Login Form
index.php
//index.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Login and Register using PDO PHP Mysql</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://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js"></script>
</head>
<body>
<div class="container">
	<h1 class="text-center" style="margin-top:30px;">Login and Register using PDO PHP Mysql</h1>
	<hr>
	<div class="row justify-content-md-center">
		<div class="col-md-5">
			<?php 
				if(isset($_SESSION['error'])){
					echo "
						<div class='alert alert-danger text-center'>
							<i class='fas fa-exclamation-triangle'></i> ".$_SESSION['error']."
						</div>
					";
 
					//unset error
					unset($_SESSION['error']);
				}
 
				if(isset($_SESSION['success'])){
					echo "
						<div class='alert alert-success text-center'>
							<i class='fas fa-check-circle'></i> ".$_SESSION['success']."
						</div>
					";
 
					//unset success
					unset($_SESSION['success']);
				}
			?>
			<div class="card">
				<div class="card-body">
				    <h5 class="card-title text-center">Sign in your account</h5>
				    <hr>
				    <form method="POST" action="login.php">
				    	<div class="mb-3">
						  	<label for="email">Email</label>
						    <input class="form-control" type="email" id="email" name="email" value="<?php echo (isset($_SESSION['email'])) ? $_SESSION['email'] : ''; unset($_SESSION['email']) ?>" placeholder="input email" required>
						</div>
						<div class="mb-3">
						  	<label for="password">Password</label>
						    	<input class="form-control" type="password" id="password" name="password" value="<?php echo (isset($_SESSION['password'])) ? $_SESSION['password'] : ''; unset($_SESSION['password']) ?>" placeholder="input password" required>
						</div>
				    <hr>
				    <div>
				    	<button type="submit" class="btn btn-primary" name="login"><i class="fas fa-sign-in-alt"></i> Login</button>
				    	<a href="register_form.php">Register a new account</a>
				    </div>
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>
Login Script
login.php
//login.php
<?php
	//start PHP session
	session_start();
 
	//check if login form is submitted
	if(isset($_POST['login'])){
		//assign variables to post values
		$email = $_POST['email'];
		$password = $_POST['password'];
 
		//include our database connection
		include 'conn.php';
 
		//get the user with email
		$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
 
		try{
			$stmt->execute(['email' => $email]);
 
			//check if email exist
			if($stmt->rowCount() > 0){
				//get the row
				$user = $stmt->fetch();
 
				//validate inputted password with $user password
				if(password_verify($password, $user['password'])){
					//action after a successful login
					$_SESSION['success'] = 'User verification successful';
				}
				else{
					//return the values to the user
					$_SESSION['email'] = $email;
					$_SESSION['password'] = $password;
 
					$_SESSION['error'] = 'Incorrect password';
				}
 
			}
			else{
				//return the values to the user
				$_SESSION['email'] = $email;
				$_SESSION['password'] = $password;
 
				$_SESSION['error'] = 'No account associated with the email';
			}
 
		}
		catch(PDOException $e){
			$_SESSION['error'] = $e->getMessage();
		}
 
	}
	else{
		$_SESSION['error'] = 'Fill up login form first';
	}
 
	header('location: index.php');
?>
Registration form
register_form.php
//register_form.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Login and Register using PDO PHP Mysql</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://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js"></script>
</head>
<body>
<div class="container">
	<h1 class="text-center" style="margin-top:30px;">Login and Register using PDO PHP Mysql</h1>
	<hr>
	<div class="row justify-content-md-center">
		<div class="col-md-5">
			<?php
				if(isset($_SESSION['error'])){
					echo "
						<div class='alert alert-danger text-center'>
							<i class='fas fa-exclamation-triangle'></i> ".$_SESSION['error']."
						</div>
					";
 
					//unset error
					unset($_SESSION['error']);
				}
 
				if(isset($_SESSION['success'])){
					echo "
						<div class='alert alert-success text-center'>
							<i class='fas fa-check-circle'></i> ".$_SESSION['success']."
						</div>
					";
 
					//unset success
					unset($_SESSION['success']);
				}
			?>
			<div class="card">
				<div class="card-body">
				    <h5 class="card-title text-center">Register a new account</h5>
				    <hr>
				    <form method="POST" action="register.php">
				    	<div class="mb-3 row">
						  	<label for="email" class="col-sm-3 col-form-label">Email</label>
						  	<div class="col-sm-9">
						    	<input class="form-control" type="email" id="email" name="email" value="<?php echo (isset($_SESSION['email'])) ? $_SESSION['email'] : ''; unset($_SESSION['email']) ?>" placeholder="input email" required>
						  	</div>
						</div>
						<div class="mb-3 row">
						  	<label for="password" class="col-sm-3 col-form-label">Password</label>
						  	<div class="col-sm-9">
						    	<input class="form-control" type="password" id="password" name="password" value="<?php echo (isset($_SESSION['password'])) ? $_SESSION['password'] : ''; unset($_SESSION['password']) ?>" placeholder="input password" required>
						  	</div>
						</div>
						<div class="mb-3 row">
						  	<label for="confirm" class="col-sm-3 col-form-label">Confirm</label>
						  	<div class="col-sm-9">
						    	<input class="form-control" type="password" id="confirm" name="confirm" value="<?php echo (isset($_SESSION['confirm'])) ? $_SESSION['confirm'] : ''; unset($_SESSION['confirm']) ?>" placeholder="re-type password">
						  	</div>
						</div>
				    <hr>
				    <div>
				    	<button type="submit" class="btn btn-success" name="register"><i class="far fa-user"></i> Signup</button>
				    	<a href="index.php">Back to login</a>
				    </div>
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>
Registraition Script
register.php
//register.php
<?php
	//start PHP session
	session_start();
 
	//check if register form is submitted
	if(isset($_POST['register'])){
		//assign variables to post values
		$email = $_POST['email'];
		$password = $_POST['password'];
		$confirm = $_POST['confirm'];
 
		//check if password matches confirm password
		if($password != $confirm){
			//return the values to the user
			$_SESSION['email'] = $email;
			$_SESSION['password'] = $password;
			$_SESSION['confirm'] = $confirm;
 
			//display error
			$_SESSION['error'] = 'Passwords did not match';
		}
		else{
			//include our database connection
			include 'conn.php';
 
			//check if the email is already taken
			$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
			$stmt->execute(['email' => $email]);
 
			if($stmt->rowCount() > 0){
				//return the values to the user
				$_SESSION['email'] = $email;
				$_SESSION['password'] = $password;
				$_SESSION['confirm'] = $confirm;
 
				//display error
				$_SESSION['error'] = 'Email already taken';
			}
			else{
				//encrypt password using password_hash()
				$password = password_hash($password, PASSWORD_DEFAULT);
 
				//insert new user to our database
				$stmt = $pdo->prepare('INSERT INTO users (email, password) VALUES (:email, :password)');
 
				try{
					$stmt->execute(['email' => $email, 'password' => $password]);
 
					$_SESSION['success'] = 'User verified. You can <a href="index.php">login</a> now';
				}
				catch(PDOException $e){
					$_SESSION['error'] = $e->getMessage();
				}
 
			}
 
		}
 
	}
	else{
		$_SESSION['error'] = 'Fill up registration form first';
	}
 
	header('location: register_form.php');
?>

Related Post