href html 内的按钮 php

href html button inside php

我正在尝试在作为提交表单结果的 .php 文件中放置一个按钮[将重定向到主页]。

php 文件是这样的:

<?php 

$user = 'root';
$pass = '';
$db = 'testdb';

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect.");

$sql = "INSERT INTO Customers (CompanyName, City, Country) VALUES ('$_POST[post_company]', '$_POST[post_city]', '$_POST[post_country]')";

if(mysqli_query($conn, $sql)){
    echo "New record created successfully!";
    $last_id = $conn->insert_id;
    echo "\nNew record has ID: " . $last_id;
}else{
    echo "Error 1: " . $sql . "<br>" .mysqli_error($conn);
}


// echo("<button onclick='location.href='index.html'>Back to Home</button>");
// this is a test I did before and didn't work

$conn->close();

?>

<div id="center_button"><button onclick="location.href='index.html'">Back to Home</button></div>

我试过将其制作成 .html 文件并放入 php 代码中,但没有成功。
我看到您可以将 html 代码放在 php 文件中,但这似乎也不起作用。我也尝试过不使用 div 标签,也尝试过放置 html 和 body 标签。
顺便说一句,数据库工作正常,它更新正常,我似乎无法显示 html 代码。


我做错了什么?

您缺少 HTML 标签。这就是为什么您看不到按钮的原因。

?>
<html>
<head>
</head>

<body>
<div id="center_button">
    <button onclick="location.href='index.html'">Back to Home</button>
</div>
</body>
</html>

编辑: 删除此行:

header("Content-Type: application/json; charset=UTF-8");

您的测试引用失败。您需要转义双引号而不是用单引号替换它们,否则您的 'index.html' link 将不起作用。因为我现在有 5 分钟的空闲时间...

echo("<button onclick=\"location.href='index.html'\">Back to Home</button>");

A string inside a string inside a string 需要小心;-)

这对我有用。

<a><?php echo( "<button onclick= \"location.href='inc/name_of_php_file.php'\">your buttons name goes here</button>");?></a>

换句话说,将您想要的 php 代码块嵌套在 'link' 锚元素内。然后添加 php 代码块,并在该代码块内添加一个 echo()。在那个回声中,你想像往常一样添加你的 HTML 代码。就好像你甚至没有在 PHP 中写作一样。

将文件夹名称和文件编辑到您想要的位置。最后编辑您希望按钮向观众显示的文本。

onclick= \"location.href='folder_name_goes_here/name_of_php_file_goes_here.php'\">你的按钮名称在这里

这应该 link 到带有您想要的标题的页面。

请记住 \",因为这非常重要。如果 " 前面没有 \,您的代码将无法正确读取由于许多 "s found nested inside each other. \ allows HTML to ignore the first " 作为 echo Sting 的结尾。