如何使用pdo将php代码分离为html?

如何使用pdo将php代码分离为html?

问题描述:

我有一个名为index.php的页面,里面,我的PHP我有CRUD的功能,我的问题是,我怎么能分开的PHP代码为HTML,并把它放在一类..请帮助我..如何使用pdo将php代码分离为html?

这里的PHP和HTML代码,我想单独

<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> 

,这里是我的课

<?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; 
    } 
    } 
+0

看看MVC模式 – Bv202

使用像MVC(模型 - 视图 - 控制器)设计模式/架构有很多的信息在互联网和S上被发现O.看看this questionthis one是一个好的开始。

关于从HTML中分离PHP:最简单的方法是使用现有的模板引擎。 Smarty是一个非常流行的,易于使用。

重要的是要分离您的业务逻辑。一个班级应该只有一个责任,称为single responsibility principle。在你的例子中,你的数据库类做了两件事:它包含数据库逻辑(执行查询)和处理你的登录系统。你应该尝试分开这些。

这些事情一开始可能会让人感到困惑。我的建议是使用MVC框架(许多PHP存在,如codeigniter,cakephp等)来理解概念。