正如您所知,在php脚本中,当您调用Return或Die时,它会阻止其他HTML代码的呈现。
如果我只想停止php脚本,但不想停止整个页面,我该怎么办?
例如:
<?php
if(!isset($_POST['txt_username']))
{
echo "Please enter your username";
return;
}
?>
<i want="this html">to be rendered</i>
我希望我的HTML代码在之后被呈现。感谢阅读。
您的问题还不清楚,但您需要停止执行PHP代码,但停止渲染HTML?您可能需要输出缓冲区或函数。
例如:
<form action="" method="post" >
<input type="text" name="txt_username" />
<input type="submit" />
</form>
<?php
function doSmth(&$password) {
if(!isset($_POST['txt_username']))
{
echo "Please enter your username";
return false;
}
$password .= "333";
echo "You password has been changed to $password";
}
$password = 128;
doSmth($password);
?>
<body>
<p> <b> Your password is <?= $password; ?> </b></p>
</body>
示例:
- 设置文本字段:
输出:
您的密码已更改为128333
您的密码是128333
- 未设置文本字段:
输出:
请输入您的用户名
您的密码是128
需要使用条件语句来包含更多PHP。然后,无论PHP的if/else语句如何,都可以呈现HTML。示例:
<?php
if( !isset($_POST['txt_username']) )
{
echo "Please enter your username";
}
else
{
//Some dditional PHP functions
}
?>
<i want="this html">to be rendered</i>
<?php
$stateOfRender = false;
if(!(isset($_SESSION['sessionid']))) {
echo "You have not logged yet. Now you are redirecting to Login Page";
header('Refresh: 5; URL = login.php');
} else {
$stateOfRender = true;
}
// In everywhere you can use this variable to control your statement
// for example:
if($stateOfRender) {
// Open DB connection and fetch user data and settle it to page.
}
?>
在我的php代码中,我使用这个方法来处理进程。通常我在数据库连接中使用它。如果dbconnection成功,我将使用控件this变量呈现页面。我希望它能帮助你。