gpt4 book ai didi

php - 回显文本出现在错误的位置

转载 作者:行者123 更新时间:2023-11-28 12:54:01 24 4
gpt4 key购买 nike

我正在用 PHP 为一个类创建一个页面,当我回显内容时,它显示在错误的位置。

这是我的 HTML 页面

<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>

<body>
<div id="main">
<h1>About</h1>

<form action="Insert.php" method="post">
<table>
<tr>
<td><span>First name:</span></td>
<td><input type="text" name="firstname"></td>
</tr>
<tr>
<td><span>Last name:</span></td>
<td><input type="text" name="lastname"></td>
</tr>
<tr>
<td><span>Age:</span></td>
<td><input type="number" name="age"></td>
</tr>
</table>

<input type="submit">
</form>

<?php include("Footer.php");?>
</div>
</body>
</html>

这是我的 PHP 页面:

<?php 
$con = mysql_connect("localhost","USERNAME","PASSWORD");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}

mysql_select_db("a7068104_world") or die("Cannot connect to database");

header("refresh:1.5; url=NamesAction.php");

$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$age = mysql_real_escape_string($_POST['age']);
$query = "SELECT * FROM names_1 WHERE fullname='$fullname'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('$firstname', '$lastname', '$fullname', '$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
}

mysql_close($con);
?>

<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>

<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>

当我回显我的 PHP 页面中的内容时,它显示在框架的最顶部,它位于

<div id="main">

我希望回显文本位于最底部

<div id="main">

有什么办法可以做到吗?感谢您的帮助!

谢谢,列奥纳多德

最佳答案

您的问题是您在提供 HTML 之前回应消息。这在这里很明显:

        if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}

因为 PHP 是服务器端语言而 HTML 是客户端语言,PHP 会在 HTML 之前处理好,这意味着它会在页面显示之前回显。因此问题出现在你的 <div id="main"></div> 之前.

解决这个问题的方法是设置一个变量

        if($result) {
$var = "Your name was successfully added to the database!";
}
else{
$var = "Your name couldn't be added to the database!";
}

在你的 <div id="main"></div> 中的某处您可以执行以下操作:

<div id="main">

<?php
if(isset($var) && !empty($var)) {
echo $var;
}

?>

</div>

关于php - 回显文本出现在错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com