【问题标题】:Is there a way to included a mysql query in mustache template?有没有办法在 mustache 模板中包含 mysql 查询?
【发布时间】:2015-02-11 12:07:38
【问题描述】:

我正在尝试将 mysql 查询中的值设置为 Mustache 中的模板。 我正在使用mustache.php 可以这样做吗?我找不到任何关于模板查询的文档。谁有更好的解决方案?

    <?php
/*
 * PHP Mustache - Basic Mustache example in PHP
 */
$servername = "localhost";
$database = "laravel";
$username = "root";
$password = "root";

try {

    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception

} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

$query = $conn->query('SELECT * FROM users');

//register mustache library
require 'Mustache/Autoloader.php';
Mustache_Autoloader::register();


//set the template string (obviously complex application will use files)
$template = 'Hello, {{name}},<br /> Your last name is {{lastname}}';


//set the template values
$values = array(
    $query = $conn->query('SELECT * FROM users');
    'name' = $row['name'];
    'lastname' = $row['lastname'];
);


//start the mustache engine
$m = new Mustache_Engine;

//render the template with the set values
echo $row['name'];
echo $row['lastname'];
echo $m->render($template, $values);
?>

【问题讨论】:

  • 这段代码有很多错误,我不知道从哪里开始。这不是创建数组的有效方法! $row 永远不会被分配。
  • @MarkusMüller 我已经包含了我的其余代码。你能告诉我哪里出错了吗?我是 php 新手

标签: php mysql mustache mustache.php


【解决方案1】:

这样试试

$statement = $conn->query('SELECT * FROM users');
$row = $statement->fetch(PDO::FETCH_ASSOC);

//start the mustache engine
$m = new Mustache_Engine;
echo $m->render($template, $row);

【讨论】:

    猜你喜欢
    • 2017-12-20
    • 2023-02-07
    • 2013-09-24
    • 2013-01-30
    • 2011-06-13
    • 2022-01-05
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    相关资源
    最近更新 更多