从数据库返回Html / Php代码

时间:2015-11-14 08:20:49

标签: php html database

我正试图制作一个' log'对于一个小项目。

日志中的信息是在数据库的另一个表中,我想从数据库中获取html表单,其中包含从其他表中获取的变量info。

数据库中的代码:

<div class="container">
<ul class="timeline">
    <li>
        <div class="timeline-panel">
            <div class="timeline-heading">
                <h4 class="timeline-title"><?php echo $player->name ?></h4>
                <p class="text-muted"><?php echo $player->time ?></p>
            </div>
            <div class="timeline-body">
                <p>While slaying <?php echo $player->npcName ?> I found an <?php echo $player->drop ?>!</p>
            </div>
        </div>
    </li>
</ul>

带功能的类:

class player
{
    public $name;
    public $time;
    public $npcName;
    public $drop;
    public $level;

    public $code;


    function getPlayer(){
        $db = new dbCon();
        $sql = 'SELECT * from player where id = 1';
        foreach($db->getCon()->query($sql) as $row ){
            $this->name = $row['name'];
            $this->time = $row['time'];
            $this->npcName = $row['npcName'];
            $this->drop = $row['drop'];
            $this->level = $row['level'];
            $db = null;
        }
    }

    function getLogForm(){
        $db = new dbCon();
        $sql = 'SELECT * from htmltemplate WHERE id = 1';

        foreach($db->getCon()->query($sql) as $row){
            $this->code = $row['code'];
        }    
    }      
}

index.php中的回声

<?php echo $player->code ?>

form code in database

Current output

1 个答案:

答案 0 :(得分:2)

由于$row['code']是一个字符串,它不会被解析,变量也不会被替换。对于此类情况,请使用sprintfstr_replace函数。

例如,您可以将html模板存储为:

<div class="timeline-panel">
    <div class="timeline-heading">
        <h4 class="timeline-title">#PLAYER_NAME#</h4>
        <p class="text-muted">#PLAYER_TIME#</p>

然后输出如:

<?php echo str_replace(
    array('#PLAYER_NAME#', '#PLAYER_TIME#'), 
    array($player->name, $player->time), 
    $player->code
);?>

当然,您应该有$player个对象。