繁体   English   中英

PHP-如果没有结果,则重定向到其他页面

[英]PHP - redirecting to other page if there are no results

如果没有结果,我想将用户重定向到其他页面。

我的意思是,我通过url传递变量并在第二页上使用,如果变量为空,则可以重定向到另一页。

但是,当用户将网址中的变量ID更改为类似

index.php?product-tit/=how+to+deal+with%20&%20item-id-pr=15

index.php?product-tit/=how+to+%20&%20item-id-pr=

页面上没有任何显示,因此在上述情况下我可以通过任何方式重定向到其他页面?

$title = urldecode($_GET['product-tit/']);
$id = $_GET['item-id-pr'];
$mydb = new mysqli('localhost', 'root', '', 'database');

if(empty($title) && empty($_GET['item-id-pr'])){
header('Location: products.php');
}
else{
$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $title, $id);
$stmt->execute();
?> 
<div>
<?php
$result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
echo wordwrap($row['price'], 15, "<br />\n", true); 
}
$mydb->close ();}
?>
</div>

您的条件要求两个变量都为空,如果要在任何一个为空时进行重定向,则应使用OR( || ):

if(empty($title) || empty($_GET['item-id-pr'])){
  header('Location: products.php');
  // make sure nothing more gets executed
  exit();
}

另请注意,您无法在header语句之前向浏览器输出任何内容。

有两件事要检查

  1. 检查传递的变量是否具有某些值。 在这种情况下,您已经应用了重定向。
  2. 如果用户更改URL参数值,例如您在示例中所要求的。 您需要验证数据库是否返回与标题和ID相对应的任何行。 如果不是,则将用户重定向到其他页面。

这可以是伪代码

<?php

$id = $_GET['item-id-pr'];
$mydb = new mysqli('localhost', 'root', '', 'database');

// I am assuming variable name is "product-tit"
$title = urldecode($_GET['product-tit']);

if(trim($title) == "" || trim($_GET['item-id-pr']) == ""){
    header('Location: products.php');
    exit;
}
$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $title, $id);
$stmt->execute();
$result = $stmt->get_result();

 if( $result->num_rows == 0 )  {
    // redirect user
     header('Location: products.php');
     exit;
 }
?> 
<div>
<?php
 while ($row = $result->fetch_assoc()) {
    echo wordwrap($row['price'], 15, "<br />\n", true); 
}
$mydb->close ();
?>
</div>

在将$_GET参数分配给其他变量并执行其他操作之前,请测试$_GET参数是否设置为空。

<?php
if (!isset($_GET['product-tit/'], $_GET['item-id-pr'])
    || empty($_GET['product-tit/'])
    || empty($_GET['item-id-pr']))
{
    header('Location: products.php');
    // although note that HTTP technically requires an absolute URI
    exit;
}
// now assign $title and $id, initialize the db, etc

暂无
暂无

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

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