4

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

He is firstly asking if its Correct or Wrong approach. And by the way its wrong approach.
Thanks for responding. The query will only ever return 1 value. In your response is $result a new variable?
To "optimise" further you could add LIMIT 1 to the SQL query
2

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.

1 Comment

Hey thanks for responding, should i just include the IF statement after the WHILE statement like i have it, or can i get rid of the WHILE statement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.