Reputation: 135
I am using this PHP script to return search input values with corresponding URL values on a MySQL database/table. The idea is to append them to a redirect to automatically jump to that page.
<?php
$searchResults = $_POST['search'];
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpass = 'pwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT url
FROM Table_1
WHERE input = '" .$searchResults."'";
mysql_select_db('database_1');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$redirect = $row['url'];
header('Location:'.$redirect);
}
To catch any input that does not match a value on Table_1 added this If statement. It will take any non relevant or misspelled inputs and redirect them to xyz.html
if (mysql_num_rows($retval) < 1) {
header('Location: xyz.html');
}
Is this incorrect? It seems to be working but I assume there must be a cleaner way of doing this/ it may be bad practice.
Upvotes: 4
Views: 659
Reputation: 147
If you are expecting only one result from the query then it would work.
But if there are multiple rows then the last row would be loaded . It would be inefficient then.
You could also directly do this:
if($retval)
{ .$row = mysql_fetch_array($retval, MYSQL_ASSOC);
header('Location:'.$row);
}
else
header('Location:xyz.html');
You wouldn't need to use the while loop if you are expecting only one row.
Upvotes: 2
Reputation: 11693
The way you use is wrong, it may cause lots of headache.
2 ways :
1.If result is x then redirect to page A.
2.If result is x then load view just similar like page A with same header ,footer.
So , as per 2nd way ,when the query is empty , Load specific view which you want.
For your example , suppose you visit a Shopping cart Site, you clicked on Shoes category , if there is no shoes, the page shows message Sorry stock is empty, no shoes
, it does not redirect you to any page if stock if empty.
Upvotes: 2