Avatar of akashj
akashj
 asked on

PHP Redirect based on an IF statement not working?

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
PHP

Avatar of undefined
Last Comment
akashj

8/22/2022 - Mon
hernst42

The compare should be done with ==, but where does $result come from? seems to be undefined all the time.
NeoAshura

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
akashj

ASKER
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
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER CERTIFIED SOLUTION
NeoAshura

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
NeoAshura

@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.
akashj

ASKER
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!
Ray Paseur

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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
NeoAshura

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.
akashj

ASKER
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

NeoAshura

did u get any errors?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
akashj

ASKER
None :)
Annoying eh?
NeoAshura

That is rather annoying like.

did you use var_dump() after the if statement?
NeoAshura

Also did u do as ray said and combine it all into 1 php file?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
akashj

ASKER
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
NeoAshura

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
akashj

ASKER

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
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
akashj

ASKER
Sorry the above is with YOUR IF statement and NOT mine
Mine doesn't display anything
NeoAshura

can you post your whole test_redirect.php file please?

Also make sure ALL 3 files are now 1 file.
Ray Paseur

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

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
akashj

ASKER
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
NeoAshura

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.
akashj

ASKER
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
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Ray Paseur

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.
Ray Paseur

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
akashj

ASKER
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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
akashj

ASKER
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)
Ray Paseur

What is the EXACT output from var_dump($thing) now?
akashj

ASKER
COMPLETED
int(1)
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
NeoAshura

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
Ray Paseur

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

akashj

ASKER
This is exactly what I am seeing
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
akashj

ASKER
Forgot to paste

LoadStatus
COMPLETED

int(1)
LoadStatus 
COMPLETED 

int(1)

Open in new window

NeoAshura

@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.

akashj

ASKER
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
Your help has saved me hundreds of hours of internet surfing.
fblack61
NeoAshura

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

akashj

ASKER
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

akashj

ASKER
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?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
NeoAshura

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

NeoAshura

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
Ray Paseur

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

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
akashj

ASKER
Thanks for the great help guys