Reputation: 67
I would like to redirect the user to other page if there are no results.
what I meant like is, I am passing variables via url and using on the second page and if the the variables are empty I am able to redirect to another page.
However when the user changes the variable id in the url to something like
index.php?product-tit/=how+to+deal+with%20&%20item-id-pr=15
to index.php?product-tit/=how+to+%20&%20item-id-pr=
Nothing is displayed on the page so is there any way that I can redirect to other page in the above condition?
$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>
Upvotes: 0
Views: 1521
Reputation: 262
There are two thing to check
Here can be pseudocode
<?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>
Upvotes: 0
Reputation: 827
Test if the $_GET
parameters are set and not empty before you assign them to other variables and do other stuff.
<?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
Upvotes: 0
Reputation: 91744
Your condition requires both variables to be empty, if you want to redirect when any is empty you should use an OR (||
):
if(empty($title) || empty($_GET['item-id-pr'])){
header('Location: products.php');
// make sure nothing more gets executed
exit();
}
Also note that you cannot output anything to the browser before a header
statement.
Upvotes: 1