Solved

PHP Redirect based on an IF statement not working?

Posted on 2010-09-06
42
638 Views
Last Modified: 2012-05-10
Hi all,

I've got 2 sections of a php file
section 1. Has header information for the redirect
section 2. Has a SQL Statement that gets a COMPLETED or RUNNING status back

The header is :
<?php
$a = "http://www.google.com";  
$b = "http://www.yahoo.com";

if ($result = "COMPLETED1")
header("Location: $a");
else
header("Location: $b");
?>

Sql is:

<?php

$result=$sql_result;
// create connection
$connection = odbc_connect("server","user","password");

// test connection
if (!$connection) {
echo "Couldn't make a connection!";
exit;
}
// create SQL statement

$sql="
SELECT
[Status]
FROM
t_status.dbo.LoadStatus";

// prepare SQL statement
$sql_result = odbc_prepare($connection,$sql);

// execute SQL statement and get results
odbc_execute($sql_result);

// format result in HTML table
odbc_result_all($sql_result,"border=1");

// free resources and close connection
//odbc_free_result($sql_result);
//odbc_close($connection);

?>


Problem is, it doesn't seem to redirect.  It's always going to $a which is Google.
I changed the = to == which then sends it to Yahoo ($b) regardless of the result.

Can anyone help me out in this?  Not sure if the order is wrong...ie: is it trying to do the redirect before running the sql/getting the result?

Appreciate it.

Thanks
0
Comment
Question by:akashj
  • 18
  • 15
  • 8
  • +1
42 Comments
 
LVL 48

Expert Comment

by:hernst42
ID: 33610333
The compare should be done with ==, but where does $result come from? seems to be undefined all the time.
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33610476
I msut agree with Hernst here $result is undefined  if it is on a seperate file it will need to be included otherwise there is no result to collect to redirect. hope this make sense.

if you need any help please just ask

Mark
0
 
LVL 5

Author Comment

by:akashj
ID: 33610626
Thanks both
Tried the == too which sends me the other way regardless of result.

As for $result, on the SQL part, its the first line
$result=$sql_result;

And $sql_result is the result of the SQL query
Bad design maybe but either way, $result is declared
0
 
LVL 6

Accepted Solution

by:
NeoAshura earned 250 total points
ID: 33610828
try the following.

Hope this helps

Mark
<?php
$a = "http://www.google.com";  
$b = "http://www.yahoo.com";

if ($result == "COMPLETED1") {
 echo "<meta http-equiv=\"refresh\" content=\"0;URL=$a\">";
 } else {
  echo "<meta http-equiv=\"refresh\" content=\"0;URL=$b\">";
 }
?>

Sql is:

<?php

$result=$sql_result;
// create connection
$connection = odbc_connect("server","user","password");

// test connection
if (!$connection) {
echo "Couldn't make a connection!";
exit;
}
// create SQL statement

$sql="
SELECT
[Status]
FROM
t_status.dbo.LoadStatus";

// prepare SQL statement
$sql_result = odbc_prepare($connection,$sql);

// execute SQL statement and get results
odbc_execute($sql_result);

// format result in HTML table
odbc_result_all($sql_result,"border=1");

// free resources and close connection
//odbc_free_result($sql_result);
//odbc_close($connection);

?>

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 33610874
Make a couple of changes to your original script.

First, add error_reporting(E_ALL) to each of the scripts.  You will be able to see if you are accidentally relying on an undefined variable.

Next use var_dump() to print out the contents of anything you are using in an "if" statement.

Now for a bit of explanation.  The single equal sign is the assignment operator.  So this statement...

if ($result = "COMPLETED1")

... Assigns the value "COMPLETED1" to the variable $result and sets TRUE.

PHP comparison operators are documented (everything is) in the online man pages.
http://php.net/manual/en/language.operators.comparison.php

If this were my application, I would do it in one script.  First query the data base, then redirect based on the results of the query.
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33610960
@Ray Paseur - If this were my application, I would do it in one script.  First query the data base, then redirect based on the results of the query.

Ditto, that its good practice to do what ray said, I now use all reporting on my scripts before they go live.
0
 
LVL 5

Author Comment

by:akashj
ID: 33611058
Thanks again both
NeoAshura - Thanks for the coding.  I actually used yours first before putting any error reporting in simply because I'm trying to hit a deadline...

Anyway tried it and despite a brief glimpse of "Completed1", it still proceeded to go to Yahoo and not Google


Ray_Paseur, thanks for the explanation.  I've fallen for the single = a few times now!
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33611073
Yeah, the single equal trips us up quite often - especially programmers who come from other languages!

Please combine this into a single script and post the latest version of your script.  We may be able to help with that.

Best to all, ~Ray
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33611130
Hmmm interesting.. sounds like to me whatever you are trying to pass as true is not being passed correctly add the reporting all error to the top of your code and post any errors u recieve me and ray will try and sort them out for you.
0
 
LVL 5

Author Comment

by:akashj
ID: 33611288
Here is a test version I am running:


<?php

error_reporting(E_ALL);

$a = "http://www.google.com";  

$b = "http://www.yahoo.com";



if ($result == "COMPLETED") {

 echo "<meta http-equiv=\"refresh\" content=\"0;URL=$a\">";

 } else {

  echo "<meta http-equiv=\"refresh\" content=\"0;URL=$b\">";

 }

?>







<?php

error_reporting(E_ALL);



$result=$sql_result;

// create connection

$connection = odbc_connect("database","user","password");



// test connection

if (!$connection) {

echo "Couldn't make a connection!";

exit;

}

// create SQL statement



$sql="

SELECT

[Status]

FROM

t_status.dbo.LoadStatus

";



// prepare SQL statement

$sql_result = odbc_prepare($connection,$sql);



// execute SQL statement and get results

odbc_execute($sql_result);



// format result in HTML table

odbc_result_all($sql_result,"border=1");



// free resources and close connection

//odbc_free_result($sql_result);

//odbc_close($connection);



?>

Open in new window

0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33611318
did u get any errors?
0
 
LVL 5

Author Comment

by:akashj
ID: 33611363
None :)
Annoying eh?
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33611377
That is rather annoying like.

did you use var_dump() after the if statement?
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33611379
Also did u do as ray said and combine it all into 1 php file?
0
 
LVL 5

Author Comment

by:akashj
ID: 33611393
I did - sorry I did forget to include it in the code above as I put it in after I posted the script

What I also did is turn off the redirect because I assume var_dump() would happen in a flash before the redirect page would come up?
But still nothing
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33611461
try changeing your redirect back to what you had it before as

if ($result = "COMPLETED1")
header("Location: $a");
else
header("Location: $b");
?>

and see if it brings any errors back
0
 
LVL 5

Author Comment

by:akashj
ID: 33611553

Notice: Undefined variable: result in C:\Inetpub\wwwroot\controller_final\users\test_redirect.php on line 7
int(6143)
Notice: Undefined variable: sql_result in C:\Inetpub\wwwroot\controller_final\users\test_redirect.php on line 20

Warning: odbc_execute() [function.odbc-execute]: SQL error: [Microsoft][ODBC SQL Server Driver]Cursor type changed, SQL state 01S02 in SQLExecute in C:\Inetpub\wwwroot\controller_final\users\test_redirect.php on line 52

Status
COMPLETED

Warning: Wrong parameter count for var_dump() in C:\Inetpub\wwwroot\controller_final\users\test_redirect.php on line 60
0
 
LVL 5

Author Comment

by:akashj
ID: 33611556
Sorry the above is with YOUR IF statement and NOT mine
Mine doesn't display anything
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33611620
can you post your whole test_redirect.php file please?

Also make sure ALL 3 files are now 1 file.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33611754
Let's try to eat this elephant a bite at a time.

Please run this and post the output.  Feel free to correct the query, as needed.
<?php
error_reporting(E_ALL);

// http://us.php.net/manual/en/function.odbc-connect.php
if (!$con = odbc_connect("database","user","password")) die('CONNECT FAILED');

http://us.php.net/manual/en/function.odbc-prepare.php
$sql="SELECT Status FROM t_status.dbo.LoadStatus";
$res = odbc_prepare($con,$sql);

// http://us.php.net/manual/en/function.odbc-execute.php
odbc_execute($res);

// http://us.php.net/manual/en/function.odbc-result.php
$thing = odbc_result($res);

// SHOW THE THING WE GOT FROM THE QUERY
echo "<pre>";
var_dump($thing);
die();

Open in new window

0
 
LVL 5

Author Comment

by:akashj
ID: 33611864
Result to the above is NULL once the file is run

All I have done is updated the SQL statement and inserted the ODBC connection, username and password
And commented out your http://us.php.net etc
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 6

Expert Comment

by:NeoAshura
ID: 33611919
That would lead me to believe that a variable is not being passed when you are selecting it from the table, can you make sure thats there is data in the tables and also can you check that your tables are called "Status" make sure its got a capital S and also check t_status etc etc.

sounds silly but ive done that a few times.
0
 
LVL 5

Author Comment

by:akashj
ID: 33612068
100% correct sql for sure
I just ran it again in Sql Server and it's fine

I've got to pop into a meeting to request an extra day on this - I'll be gone for a few hours - can we pick this up then or tomorrow?

Feel free to throw any more suggestions and I can try tonight either way

Thanks for both your help/patience so far
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33612195
Please see the man page here about NULL
http://us.php.net/manual/en/function.odbc-result.php
Returns the string contents of the field, FALSE on error, NULL for NULL data, or TRUE for binary data.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33612203
Also, you might want to add a check to see what is returned from this function:
http://us.php.net/manual/en/function.odbc-prepare.php
0
 
LVL 5

Author Comment

by:akashj
ID: 33613724
Right few updates

I know for 100% that my result IS coming out as COMPLETED

BUT, it seems to be something to do with the order of how things are loading.  For instance, the all-in-one file is doing the redirect first, then the sql statement.

I tested this theory by putting $result in the actual address so: http://www.google.co.uk/$result
The end result of this is http://www.google.co.uk
(So it does not see the variable).

I then hardcoded $result to be $result = COMPLETED

Once I re-run the file, the output address was http://www.google.co.uk/COMPLETED


I also feel I need to apologise as there has been some confusion.  This has always been in ONE file.  It was probably my mistake in bad design that I had multiple <? tags within the one file.


So I'm not quite sure where to go from here but if I can somehow load the file, let it run the SQL statement FIRST and then let it do the redirect, we've got a result.

Appreciate the help as always
0
 
LVL 5

Author Comment

by:akashj
ID: 33613825
And another update
I change Ray's script slightly to say $thing = odbc_result_all($res);
(added _all after odbc_result)

and I get

Status
COMPLETED
int(1)
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33613897
What is the EXACT output from var_dump($thing) now?
0
 
LVL 5

Author Comment

by:akashj
ID: 33613928
COMPLETED
int(1)
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33613958
Im pleased to see this is getting resolved, it is late here and im going to bed now, but if this is not resolved by the time i get to work tomorrow morning at 9am i will look at it again and help out where i can also.

Speak soon.

Mark
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33613989
That does not make sense.  var_dump() does not produce output like that.  It tells the data type.  We are expecting something like this (see code snippet).

Please copy and paste the output, thanks.
array(1) { ["COMPLETED"]=>  int(1) } 

Open in new window

0
 
LVL 5

Author Comment

by:akashj
ID: 33615618
This is exactly what I am seeing
0
 
LVL 5

Author Comment

by:akashj
ID: 33615620
Forgot to paste

LoadStatus
COMPLETED

int(1)
LoadStatus 
COMPLETED 

int(1)

Open in new window

0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33615958
@Ray - Based on           array(1) { ["COMPLETED"]=>  int(1) }                and he is seeing

LoadStatus
COMPLETED

int(1)

Isnt that what hes ment to see? it means that the array is working. so if that shows the array is working. Is the rest of your file still present after the Vardump? if not add it back in and see what happens. I may be wrong here and im sure Ray will correct me if i am but Int 1 shows that the variable is being set from the array so it turn shows that your SQL is working.

This may be my lack of experiance compared to ray and tbh it proberly is.. but what happens if you move the re-direct after the SQL query has completed and the variable is set? i realise that the if statement only runs if the status is complete but at this point its worth a try right?

Mark.

0
 
LVL 5

Author Comment

by:akashj
ID: 33615985
Thanks Mark,

So if I move the redirect AFTER the SQL statement, the redirect does not...redirect
From what I've been reading, a redirect HAS to be in the header part of the file (or above anything else)

I'm trying another way around to maybe split it into multiple files:
Page 1. Run SQL and result into a variable that then moves to Page 2.
Page 2. Get's that stored variable and uses it in the redirect to either Page 3 or Page 4 depending on the result.

But my PHP is a little rusty too and I'm not sure how to store and pass a odbc_result to another page
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33616042
Again im sure if im wrong ray will correct me, hes on a diffrent time zone to me so he should be on later on, you can include a whole script as variable and pass it to the next page. so you could store the SQL query and pass it to the next page for example...

Im persumeing once its been passed into the new page you will then be able to call the variable because it is now included in the file to redirect to the nextp age.
ob_start(); // start buffer
include ("redirect-test.php");
$content = ob_get_contents(); // assign buffer contents to variable
ob_end_clean(); // end buffer and remove buffer contents
echo $content;

Open in new window

0
 
LVL 5

Author Comment

by:akashj
ID: 33616138
Right I've just tried the code below
This basically does a redirect AFTER the SQL statement
Still does not seem to work though... It works correctly in that it goes to google but when I made a type in the result (C0MPL3TED), it SHOULD have gone to yahoo but instead, it carried on going to google.

<?php

ini_set('display_errors', 'On');

error_reporting(E_ALL);





// create connection

$connection = odbc_connect("database","user","password");

// test connection

if (!$connection) {

echo "Couldn't make a connection!";

exit;

}

// create SQL statement



$sql="

SELECT

[Status]

FROM

t_status.dbo.LoadStatus";



// prepare SQL statement

$sql_result = odbc_prepare($connection,$sql);



// execute SQL statement and get results

odbc_execute($sql_result);



// format result in HTML table

//odbc_result_all($sql_result,"border=1");



// free resources and close connection



echo odbc_result_all($sql_result);

sleep(5);

if (odbc_result_all($sql_result) == 'COMPLETED')

{

printf("<script>location.href='http://www.google.com'</script>");

}

else

{

// show other stuffs

printf("<script>location.href='http://www.yahoo.com'</script>");

}



odbc_free_result($sql_result);

odbc_close($connection);

var_dump($sql_result)



?>

Open in new window

0
 
LVL 5

Author Comment

by:akashj
ID: 33616253
Believe it or not... I've finally got it working
I'm going to leave this open for the rest of the day just to ensure it does work 100% but basically I've used a combination of my script, and parts of both your scripts.
In the end, it turned out to be something very very silly... I applied a TRIM to the result and that fixed it

Despite not having spaces before or after, it seems to need it to see the result.  Maybe a PHP/SQL Server issue?
0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33616304
Looks like your using JAva script there to try and move the window.

try the following.. also do u get any errors and also what does var_dump show?
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);


// create connection
$connection = odbc_connect("database","user","password");
// test connection
if (!$connection) {
echo "Couldn't make a connection!";
exit;
}
// create SQL statement

$sql="
SELECT
[Status]
FROM
t_status.dbo.LoadStatus";

// prepare SQL statement
$sql_result = odbc_prepare($connection,$sql);

// execute SQL statement and get results
odbc_execute($sql_result);

// format result in HTML table
//odbc_result_all($sql_result,"border=1");

// free resources and close connection

echo odbc_result_all($sql_result);
sleep(5);
if (odbc_result_all($sql_result) == 'COMPLETED')
{
printf("<script>window.location='http://www.google.com'</script>");
}
else
{
// show other stuffs
printf("<script>window.location.='http://www.yahoo.com'</script>");
}

odbc_free_result($sql_result);
odbc_close($connection);
var_dump($sql_result)

?>

Open in new window

0
 
LVL 6

Expert Comment

by:NeoAshura
ID: 33616324
Quite possibly it would be cool, if you could post the whole code you resolved it with incase people have this problem in future, im really pleased that you managed to get it worknig and that you are going to be able to meet your deadline. i think all 3 of us may of learned something here in this question. always valuable espesically in my experiance with only 1 and a half years php behind me.

Hopefully it will still work at the end of the day if not im sure me and ray can help u again.

Best of luck
Mark
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33616534
I'll sign off on this question now.  As you can see from the snippet below, var_dump() shows data type, length and content.  You need to know all three things to formulate a correct if() statement based on the data.  Since this was a data-dependent issue and the if() statement was the central issue here, I asked for the var_dump() output.  This is the critical first step in the debugging process.

The next step, once we knew exactly what to expect from the query, would be to formulate the if() statement.

The final step, once we had exactly the if() statement, would be to render the script silent and perform the redirect.

The best way to redirect is to set the $url variable to the new address and use the HTTP headers (you must do this before any browser output):
header("Location $url"); // TELL THE BROWSER THE NEW ADDRESS
exit; // DO NOT OMIT THIS

Use of meta tags or window.location may not be as "well thought of" or deprecated at some level, but those should work, too.

This incremental or iterative way of debugging an isolated script issue will be very helpful to you.  When the question is about "what data have I got" no amount of guessing substitutes for simple data visualization.  The wise authors of PHP knew that when they equipped the language with var_dump().
<?php // RAY_temp_akashj.php
echo "<pre>";

// SHOW AN ARRAY
$thing = array( 'COMPLETED' => 1 );
var_dump($thing);

// SHOW AN INTEGER
$thing = 1;
var_dump($thing);

// SHOW A BOOLEAN
$thing = TRUE;
var_dump($thing);

// SHOW A STRING
$thing = 'COMPLETED';
var_dump($thing);

// SHOW ANOTHER STRING THAT WILL LOOK THE SAME WHEN PRINTED IN HTML
$thing = 'COMPLETED ';
var_dump($thing);

/* *********** OUTPUT OF CODE EXECUTION FOLLOWS

array(1) {
  ["COMPLETED"]=>
  int(1)
}
int(1)
bool(true)
string(9) "COMPLETED"
string(10) "COMPLETED "

Open in new window

0
 
LVL 5

Author Closing Comment

by:akashj
ID: 33690564
Thanks for the great help guys
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now