-2

我试图避免两次查询我的数据库:设置<title>属性和回显页面标题。我只想查询一次:

例子:

<html>
  <head>
  <?php
    // how should I use here ob_start() ? Is there any other possible way to achieve this?
    $title = "";
    echo '<title>', $title, '</title>'; // this should be in the end <title>value of $row['page_title']</title>
  ?>
  </head>
  <body>
     <?php
       $sql = $mysqli->query("MY QUERY");
       $row = $sql->fetch_assoc();
       $title = $row['page_title']; // I want that this assignment to set the variable in the top
       // I know that for this job I can use ob_start() but I didn't used it until now
       // and I will really appreciate any help from you.

     ?>
     <h1><?php echo $title; ?></h1>
  </body>
</html>

我知道我可以在回显title属性之前进行查询,但我不想那样做。你有什么建议吗?或者你能告诉我如何使用那个ob_start()/ob_clean()功能吗?

谢谢!

4

2 回答 2

1

将查询移到代码顶部并重用变量!

<?php
       $sql = $mysqli->query("MY QUERY");
       $row = $sql->fetch_assoc();
       $title = $row['page_title']; 
?>
<html>
  <head>
  <?php echo '<title>', $title, '</title>'; ?>
  </head>
  <body>
     <h1><?php echo $title; ?></h1>
  </body>
</html>
于 2012-12-05T13:29:34.407 回答
0

ob_start();,在通常意义上,不会帮助你。但是,您可以使用这样的丑陋解决方案:

ob_start();
echo '
  <html>
    <head>
      <title>{title}</title>
    </head>
  <body>
    ';
$header = ob_get_clean();

// and then, when you know your title
echo str_replace('{title}', $known_title, $header);

但我强烈建议采取另一种方法。在收集完所有数据并且您知道有关所需模板的所有详细信息后,您需要选择并填写模板。如果你开始抢先呼应不同的部分,你会遇到越来越多的麻烦。现在您需要更改某些页面的标题。然后你需要为特定页面添加 css 文件,你将不得不再次做那个丑陋的事情。为什么不以正确的方式去做呢?

于 2012-12-05T14:13:50.027 回答