Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European PHP Hosting - HostForLIFE :: User Management With Location Track Using PHP/MySQL

clock November 23, 2021 06:25 by author Peter

In this article, I will explain how to perform user management with their location in PHP using XAMPP server. This application is used to add the user name, email, mobile number and address and is also able to edit details and remove users. Download the XAMPP server in https://www.apachefriends.org/download.html. We can learn using this article curd operation and basic core PHP and MySQL server databases connection. Also all added user can view the google map location.

Here will see MySQL database connection, fetch all user details also insert, update and delete.
Create DB and Table in MySQL database

Using phpMyAdmin XAMPP server we can create our db.My database name is usermanagement.

To create table follow this below set of queries.

-- Database: `usermanagement`
-- ---------------------------
-- Table structure for table `tblusers`

CREATE TABLE `tblusers` (
  `ID` int(10) NOT NULL,
  `FirstName` varchar(200) DEFAULT NULL,
  `LastName` varchar(200) DEFAULT NULL,
  `MobileNumber` bigint(10) DEFAULT NULL,
  `Email` varchar(200) DEFAULT NULL,
  `Address` mediumtext DEFAULT NULL,
  `CreationDate` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `Country` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Dumping data for table `tblusers`

INSERT INTO `tblusers` (`ID`, `FirstName`, `LastName`, `MobileNumber`, `Email`, `Address`, `CreationDate`, `Country`) VALUES
(13, 'Peter', 'S', 9879887711, '[email protected]', 'New York', '2020-10-16 13:51:16', NULL),
(14, 'Scott', 's', 4654564111, '[email protected]', 'London', '2020-10-16 15:21:12', NULL),
(20, 'Leo', 'boss', 908776543, '[email protected]', 'london', '2021-03-03 05:42:04', NULL),
(34, 'Thea', 's', 2323298830, '[email protected]', 'London\r\n', '2021-10-19 06:36:47', NULL),
(36, 'Mark', 'd', 2987123390, '[email protected]', 'Sweden', '2021-10-19 06:36:02', NULL),
(43, 'Friedrich', 'f', 3333333333, '[email protected]', 'Germany', '2021-10-19 06:36:28', NULL);

-- Indexes for dumped tables

-- Indexes for table `tblusers`
ALTER TABLE `tblusers`
  ADD PRIMARY KEY (`ID`);

-- AUTO_INCREMENT for dumped tables

-- AUTO_INCREMENT for table `tblusers`

ALTER TABLE `tblusers`
  MODIFY `ID` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48;
COMMIT;

PHP database connection using MySQL
Create a database.php file and write below code to connect Database
<?php
$con=mysqli_connect("localhost","root","","usermanagement");
if(mysqli_connect_errno($con))
{
  echo "connection failed".mysqli_connect_error($con);
}
?>


index.php
index.php file is our application first page to view all added users.
<?php
$ret = mysqli_query($con, "select * from tblusers");
$cnt = 1;
$row = mysqli_num_rows($ret);
if ($row > 0)
{
    while ($row = mysqli_fetch_array($ret))
    {

?>
    <!--Fetch the Records -->
        <tr>
            <td><?php echo $cnt; ?></td>
            <td><?php echo $row['FirstName']; ?> <?php echo $row['LastName']; ?></td>
            <td><?php echo $row['Email']; ?></td>
            <td><?php echo $row['MobileNumber']; ?></td>
            <td> <?php echo $row['CreationDate']; ?></td>
            <td>
  <a href="read.php?viewid=<?php echo htmlentities($row['ID']); ?>" class="view" title="View" data-toggle="tooltip"><i class="material-icons">&#xE417;</i></a>
                <a href="edit.php?editid=<?php echo htmlentities($row['ID']); ?>" class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
                <a href="index.php?delid=<?php echo ($row['ID']); ?>" class="delete" title="Delete" data-toggle="tooltip" onclick="return confirm('Do you really want to Delete ?');"><i class="material-icons">&#xE872;</i></a>
            </td>
      <td> <a href="weblocation.php?id=<?php echo ($row['ID']); ?>" class="location" title="location" data-toggle="tooltip"><i class="fa fa-map-marker" aria-hidden="true"></i></a></td>
        </tr>
        <?php
        $cnt = $cnt + 1;
    }
}


insert.php
insert.php file is used to add user information like user name, email, mobile number, and address.
<?php
//Databse Connection file
include ('dbconnection.php');
if (isset($_POST['submit']))
{
    //getting the post values
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $contno = $_POST['contactno'];
    $email = $_POST['email'];
    $add = $_POST['address'];
    //Query select
    $selectquery = mysqli_query($con, "select Email,MobileNumber from  tblusers");
    $cnt = 1;
    while ($row = mysqli_fetch_array($selectquery))
    {

        if ($row['Email'] == $email)
        {

            echo "<script>alert('email is already exists');</script>";
            echo "<script type='text/javascript'> document.location ='insert.php'; </script>";
        }
        if ($row['MobileNumber'] == $contno)
        {
            echo "<script>alert('contactno is already exists');</script>";
            echo "<script type='text/javascript'> document.location ='insert.php'; </script>";
        }
        $cnt = $cnt + 1;
    }
    // Query for data insertion
    $query = mysqli_query($con, "insert into tblusers(FirstName,LastName, MobileNumber, Email, Address) value('$fname','$lname', '$contno', '$email', '$add' )");
    if ($query)
    {
        echo "<script>alert('You have successfully inserted the data');</script>";
        echo "<script type='text/javascript'> document.location ='index.php'; </script>";
    }
    else
    {
        echo "<script>alert('Something Went Wrong. Please try again');</script>";
    }
}
?>

edit.php
We can edit all user details in edit.php
<?php
//Database Connection
include ('dbconnection.php');
if (isset($_POST['submit']))
{
    $eid = $_GET['editid'];
    //Getting Post Values
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $contno = $_POST['contactno'];
    $email = $_POST['email'];
    $add = $_POST['address'];
    //Query for data updation
    $query = mysqli_query($con, "update  tblusers set FirstName='$fname',LastName='$lname', MobileNumber='$contno', Email='$email', Address='$add' where ID='$eid'");

    if ($query)
    {
        echo "<script>alert('You have successfully update the data');</script>";
        echo "<script type='text/javascript'> document.location ='index.php'; </script>";
    }
    else
    {
        echo "<script>alert('Something Went Wrong. Please try again');</script>";
    }
}
?>


delete.php
delete.php file is used to remove each user separately
<?php
//database conection  file
include ('dbconnection.php');
//Code for deletion
if (isset($_GET['delid']))
{
    $rid = intval($_GET['delid']);
    $sql = mysqli_query($con, "delete from tblusers where ID=$rid");
    echo "<script>alert('Data deleted');</script>";
    echo "<script>window.location.href = 'index.php'</script>";
}
?>


weblocation.php
Location of users we can track via Google Maps.
<?php
include ('dbconnection.php');
$eid = $_GET['id'];
$ret = mysqli_query($con, "select Address from tblusers where ID='$eid'");
$row = mysqli_fetch_array($ret);
$selectall = mysqli_query($con, "select Address,FirstName,LastName from tblusers where Id !='$eid'");
if (mysqli_num_rows($selectall) > 0) echo "<b>Same Location users</b><br>";
while ($rows = mysqli_fetch_array($selectall))
{
    if ($rows['Address'] == $row['Address'])
    {
        $match = 1;
        echo $rows['FirstName'] . '' . $rows['LastName'] . '<br>';

    }
}
echo "<br>";
$add = $row['Address'];
?>
<html>
<div class="text-center"><a href="index.php">Back</a></div>
<div>
 <iframe width="50%" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?q=<?=$add; ?>&amp;ie=UTF8&amp;&amp;output=embed"></iframe><br />
</div>
</html>



European PHP Hosting - HostForLIFE.eu :: MySQL PHP MVC CRUD Without Framework

clock August 14, 2020 12:50 by author Peter

This tutorial is for beginners or students. I created a functionality to add, edit and delete a record in PHP with MVC logic without Framework. Also,  explained how to create an MVC pattern in PHP. I hope it will be helpful for you to add a data table in your program.

Building Our MVC Framework Pattern in PHP
You might be wondering why we would even need to create our own framework when there are already so many good choices out there. The reason for this is so that we can gain an understanding of the underlying principles of MVC.

As we learn more about these principles, we will grow in our understanding of why the excellent MVC frameworks do things the way they do. We are not learning how to create an application in Zend Framework, or in CakePHP. We are learning how MVC works, and by extension, how these frameworks have built upon (or deviated from) the way in which we would expect an MVC framework to be built.
Section 1

Config.php is used to connect the mysql database to create a connection parameter for mysql host,user,password and database name.
<?php 
class config   
{    
function __construct() { 
$this->host = "localhost"; 
$this->user  = "root"; 
$this->pass = "welcome"; 
$this->db = "mydb13"; 


?> 


A small part of the code in index.php is used to setup a controller object and call mvcHandler() to view the default page list.php.
<?php 
session_unset(); 
require_once  'controller/sportsController.php';         
$controller = new sportsController();    
$controller->mvcHandler(); 
?> 


In the model folder, create one class for table structure, its named sports and has field and message field to hold messages and data.
<?php 
class sports 

// table fields 
public $id; 
public $category; 
public $name; 
// message string 
public $id_msg; 
public $category_msg; 
public $name_msg; 
// constructor set default value 
function __construct() 

$id=0;$category=$name=""; 
$id_msg=$category_msg=$name_msg=""; 


?> 


Section 2
The second section is a sportsModel class structure. We are going to explain and show insertRecord(), updateRecord(),selectRecord() and insertRecord(). The sportsModel class is used to access the function sportsController. The sportsModel class constructor receives a mysql connection parameter to work with the database.
<?php 

class sportsModel 

// set database config for mysql 
function __construct($consetup) 

$this->host = $consetup->host; 
$this->user = $consetup->user; 
$this->pass =  $consetup->pass; 
$this->db = $consetup->db;                                 

// open mysql data base 
public function open_db() 

$this->condb=new mysqli($this->host,$this->user,$this->pass,$this->db); 
if ($this->condb->connect_error)  

die("Erron in connection: " . $this->condb->connect_error); 


// close database 
public function close_db() 

$this->condb->close(); 

// insert record 
public function insertRecord($obj){ } 
//update record 
public function updateRecord($obj){ } 
// delete record 
public function deleteRecord($id){ }    
// select record      
public function selectRecord($id){ } 


?> 


Section 3
Section 3 is the controller code part. The sportsController has mvcHandler() and the CRUD functions insert(), update(),delete() and list(). mvcHandler() receives request and execute. This request shows views according to call request by user.
// insert record 
public function insertRecord($obj) 

try 
{    
    $this->open_db(); 
    $query=$this->condb->prepare("INSERT INTO sports (category,name) VALUES (?, ?)"); 
    $query->bind_param("ss",$obj->category,$obj->name); 
    $query->execute(); 
    $res= $query->get_result(); 
    $last_id=$this->condb->insert_id; 
    $query->close(); 
    $this->close_db(); 
    return $last_id; 

catch (Exception $e)  

    $this->close_db();    
    throw $e; 


//update record 
public function updateRecord($obj) 

try 
{    
    $this->open_db(); 
    $query=$this->condb->prepare("UPDATE sports SET category=?,name=? WHERE id=?"); 
    $query->bind_param("ssi", $obj->category,$obj->name,$obj->id); 
    $query->execute(); 
    $res=$query->get_result();                        
    $query->close(); 
    $this->close_db(); 
    return true; 

catch (Exception $e)  

    $this->close_db(); 
    throw $e; 


// delete record 
public function deleteRecord($id) 
{    
try{ 
    $this->open_db(); 
    $query=$this->condb->prepare("DELETE FROM sports WHERE id=?"); 
    $query->bind_param("i",$id); 
    $query->execute(); 
    $res=$query->get_result(); 
    $query->close(); 
    $this->close_db(); 
    return true;     

catch (Exception $e)  

    $this->closeDb(); 
    throw $e; 
}        
}    
// select record      
public function selectRecord($id) 

try 

    $this->open_db(); 
    if($id>0) 
    {    
        $query=$this->condb->prepare("SELECT * FROM sports WHERE id=?"); 
        $query->bind_param("i",$id); 
    } 
    else 
    {$query=$this->condb->prepare("SELECT * FROM sports");    }        
     
    $query->execute(); 
    $res=$query->get_result();    
    $query->close();              
    $this->close_db();                 
    return $res; 

catch(Exception $e) 

    $this->close_db(); 
    throw $e;    

 


Section Four
Section four is the view part, when mvcHandler() receives a request and executes the request, it shows views for user. We have created three views in the view folder, which is insert, update and list, which all have HTML design. These views work with controller, and the controller works with model to get or set records in a database table.
<div class="wrapper">   
<div class="container-fluid">   
<div class="row">   
<div class="col-md-12">   
    <div class="page-header clearfix">   
        <a href="index.php" class="btn btn-success pull-left">Home</a>   
        <h2 class="pull-left">Sports Details</h2>   
        <a href="view/insert.php" class="btn btn-success pull-right">Add New Sports</a>   
    </div>   
    <?php   
        if($result->num_rows > 0){   
            echo "<table class='table table-bordered table-striped'>";   
                echo "<thead>";   
                    echo "<tr>";   
                        echo "<th>#</th>";                                           
                        echo "<th>Sports Category</th>";   
                        echo "<th>Sports Name</th>";   
                        echo "<th>Action</th>";   
                    echo "</tr>";   
                echo "</thead>";   
                echo "<tbody>";   
                while($row = mysqli_fetch_array($result)){   
                    echo "<tr>";   
                        echo "<td>" . $row['id'] . "</td>";                                           
                        echo "<td>" . $row['category'] . "</td>";   
                        echo "<td>" . $row['name'] . "</td>";   
                        echo "<td>";   
                        echo "<a href='index.php?act=update&id=". $row['id'] ."' title='Update Record' data-toggle='tooltip'><i class='fa fa-edit'></i></a>";   
                        echo "<a href='index.php?act=delete&id=". $row['id'] ."' title='Delete Record' data-toggle='tooltip'><i class='fa fa-trash'></i></a>";   
                        echo "</td>";   
                    echo "</tr>";   
                }   
                echo "</tbody>";                               
            echo "</table>";   
            // Free result set   
            mysqli_free_result($result);   
        } else{   
            echo "<p class='lead'><em>No records were found.</em></p>";   
        }   
    ?>   
</div>   
</div>           
</div>   
</div>   


Conclusion
This article showed and explained to beginners how to make an MVC framework pattern in PHP. You might be wondering why we would even need to create our own framework when there are already so many good choices out there. The reason for this is so we can gain an understanding of the underlying principles of MVC.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in