【问题标题】:PHP & MySQL empty recordsPHP & MySQL 空记录
【发布时间】:2023-03-11 20:25:01
【问题描述】:

在我的数据库中,我一直在获取由其自己的 ID 显示的单个记录。在 URL 中是这样的:site.com/index.php?id=1。但是,如果我用不存在的 ID 写入地址(如 site.com/index.php?id=3553255,它会将我发送到我用作“模板”的页面,但没有数据(空页面)。

如果记录为空或不存在,我如何发送标头状态 404?

这是我的代码:

<?php

if(isset($_GET['id'])) {

$id = mysql_escape_string($_GET['d']);

include 'mysql_conexion.php';

$sql=" SELECT * FROM portfolio WHERE id='$id'";
$data=mysql_query($sql,$conexion);

while ($row=mysql_fetch_array($data)) {
      $id=$row['id'];
      $heading=$row['heading'];
 }

echo "<div><h1>$heading</h1></div>";

}

mysql_free_result($data); 
mysql_close($conexion);

?>

注意: 我试过用 else 和 header 函数 “else {header ('HTTP/1.0 404 Not Found', true, 404);} exit;”和标题:位置, 但没用。

感谢您的关注。

【问题讨论】:

  • 你应该在调用header()之前打印任何东西,这就是它不起作用的原因。

标签: php mysql get http-status-code-404


【解决方案1】:

尝试输入一个基本上看起来像这样的简单 if 语句:

$numberofRows = count($cars);

if ($numberofRows == 0){

echo '<meta http-equiv="refresh" content="0; url=http://example.com/" />';

}

else{
while ($row=mysql_fetch_array($data)) {
      $id=$row['id'];
      $heading=$row['heading'];
 }

echo "<div><h1>$heading</h1></div>";

}

mysql_free_result($data); 
mysql_close($conexion);
}
?>

这将使用您的查询来查看与它匹配的行数。如果数字为 0,它会将用户重定向到 404 页面。

希望这会有所帮助。

【讨论】:

  • 误读使用提供的相同代码,只需在您的 html
    之前执行此过程。在 if 内回显你想要的标题。
猜你喜欢
  • 2011-10-24
  • 2013-02-13
  • 1970-01-01
  • 2021-11-21
  • 2011-12-10
  • 2012-05-10
  • 2019-12-13
  • 2013-12-31
  • 2019-03-20
相关资源
最近更新 更多