PHP Sessions

~J~

~J~

Soldato
Joined
20 Oct 2003
Posts
7,558
Location
London
Only been using PHP since last Thursday, so all this is totally new and I don't know if it's possible.

In a nushell I've got the following code in a page:

<?php

require("connect.php");



$txtAction = $_REQUEST['txtAction'];

$txtName = $_REQUEST['txtName'];



if ($txtAction == 'Find')

{

$sql= "SELECT name, town, county FROM customers WHERE name LIKE '%$txtName%'";

$result = @mysql_query($sql,$dbh) or die (mysql_error());



$num = mysql_num_rows($result);



if ($num > 0 )

{

$_SESSION["Results"]=$result;

header ('Location: findresults.php');





}

}


?>

Which, if results are found, go to another page which lists the results.

The PHP on the 'findresults' page is:

<?php

require("connect.php");



$result=$_SESSION["Results"];



while ($row = mysql_fetch_array($result))

{

$name = $row['name'];

$town = $row['town'];

$county = $row['county'];

echo "<p>$name</p>";

}





?>

But I get an error of "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in html/findresults.php on line 6"

Any ideas what I'm doing wrong, or is it not possible? I'd have thought by passing $Results in a session I'd be able to retrieve it's entireity on the calling page!
 
You need to start a session before you can pass any variables too it. Put session_start(); at the top of each of your pages.
 
Doh!

OK, done that, but it only seems to work if I pass the $SQL into a session and call the database twice (which seems a bit of a hammering on the SQL Server).

Can passing the $results array not be done then?
 
Please escape your user input!

As for the the query result not working across requests, that's because the mysql_query() function returns a PHP resource, not an array. Resources don't actually contain any data themselves, but rather point to where the data are held. Since the data themselves do not persist across requests, storing the result in a session variable won't work.

You're probably best of processing the result and building an array of all the rows, then storing that in a session variable and redirecting.
 
Last edited:
Cheers Inquisitor, the SQL Injection stuff is been taken care of my one of the lads in house so I think we're covered on that thanks.

Have done what you suggested about the array and that worked a charm, so again, thanks for the tip on that one.

Even learnt how to use Explode today so I'm pretty pleased with myself!!
 
Back
Top Bottom