简体   繁体   English

在循环中调用PHP中的变量

[英]calling a variable in PHP while loop

i have a website structure as follow 我有一个网站结构如下

<div id="title">
<h1> //call $title here after executing loop </h1>
</div>
<?php 
   ...
     while ($row = $result->fetch_assoc()) { $title = $row['title']; ?>

<h2> this is the <?php echo $title;?> </h2>
<?php } ?>

is there a way i could still use or call the $title variable on an html element on top of the while loop statement? 有没有办法我仍然可以在while循环语句之上的html元素上使用或调用$title变量?

whenever i call it above the while loop i get errors like Undefined variable: id.. 每当我在while循环上面调用它时,我会得到像Undefined variable: id..这样的错误Undefined variable: id..

edit: change id into 'title' instead 编辑:将ID更改为“标题”

PHP will read code line by line so variable can't be used before declaration. PHP将逐行读取代码,因此在声明之前不能使用变量。

Only one option is to move loop above your div, get html from loop inside variable and print it later. 只有一个选项是在你的div上方移动循环,从变量中的循环中获取html并稍后打印它。

I think that you've got only one row in that loop so use this code instead. 我认为你在该循环中只有一行,所以请使用此代码。

$row = $result->fetch_assoc();
$title = $row['title'];
echo '<h2> this is the '.$title.' </h2>';

If you're only retrieving a single row, you don't need the loop: 如果您只检索单行,则不需要循环:

<?php
$row = $result->fetch_assoc();
$title = $row['title'];
?>

<div id="title">
    <h1><?php echo $title; ?></h1>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM