【问题标题】:Returning Html/Php code from a database从数据库返回 Html/Php 代码
【发布时间】:2015-11-14 08:20:48
【问题描述】:

我正在尝试为一个小项目制作“日志”。

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

数据库中的代码:

<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

【问题讨论】:

    标签: php html database


    【解决方案1】:

    由于$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 对象可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 2014-01-18
      • 1970-01-01
      相关资源
      最近更新 更多