0

I have a page called index.php and inside that php i have the function of CRUD and my problem is that how can i separate the php code to html and put it in a class..please help me..

here's the php and html code i want to separate

<label class="Land_Type">
        <span>Land Type</span>
                <?php
                    include_once 'dbconfig.php';

                    $sql = "SELECT Land_Type_Name FROM land_type";
                    $stmt = $DB_con->prepare($sql);
                    $stmt->execute();
                    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

                        if ($stmt->rowCount() > 0)
                        {
                ?>
            <select name="Land_Type">
                <option selected="selected" value="">---</option>
                    <?php
                        foreach ($results as $row)
                        {
                    ?>
                <option value="<?php echo $row['Land_Type_Name']; ?>"><?php echo $row['Land_Type_Name']; ?></option>
                <?php
                    }
                ?>
            </select>
                <?php
                    }
                ?>
    </label>

and here is my class

<?php

class crud
{
private $db;

function __construct($DB_con)
{
$this->db = $DB_con;
}
public function login($uname,$upass)
{
try
{
  $stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname LIMIT 1");
  $stmt->execute(array(':uname'=>$uname));
  $userRow=$stmt->fetch(PDO::FETCH_ASSOC);

    if($stmt->rowCount() > 0)
    {
    if(password_verify($upass, $userRow['user_pass']))
    {
      $_SESSION['user_session'] = $userRow['user_id'];
      return true;
    }
    else
    {
      return false;
    }
   }
  }
    catch(PDOException $e)
  {
    echo $e->getMessage();
   }
  }

  public function is_loggedin()
    {
    if(isset($_SESSION['user_session']))
    {
    return true;
    }
  }

1 Answers1

0

Use a design pattern/architecture like MVC (Model-View-Controller) There's a lot of information to be found about this on the internet and on SO. Have a look at this question and this one for a good start.

Regarding seperating PHP from HTML: the easiest way is to use an existing template engine. Smarty is a very popular one and easy to use.

The important thing is to seperate your business logic. A class should have only one responsibility, which is called the single responsibility principle. In your example, your database class is doing 2 things: it contains the database logic (executing queries) and handling your login system. You should attempt to seperate these.

These things can be pretty confusing in the beginning. My advice is to use a MVC framework (many exist for PHP like codeigniter, cakephp,...) to understand the concepts.

Community
  • 1
  • 1
Bv202
  • 3,924
  • 13
  • 46
  • 80