Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using an SQL statement and a starting a SESSION together

Status
Not open for further replies.

Sitehelp

Technical User
Joined
Feb 4, 2004
Messages
142
Location
GB
Hello all! ok I have a quick question, on my login page I have a session that opens so that the users details can be opened on the next few pages. The username and password box are in the same form and the session, as its supposed to, is declared at the top of the code b4 the form iteself, however, when I have the form as:

<form action = &quot; Logged In/WelcomeUserPage.php&quot;>


It works great but it does not check the username and password using the sql at the top of the code. When I have the form as:

<form method=&quot;post&quot; onReset=&quot;MM_displayStatusMsg('Please enter your ClientID and Password');return document.MM_returnValue&quot;>

The SQL at the top of the page cross checks the user in the DB and logs them in if the fields are correct but does not implement the session and therefore I cannot get the users details on the other pages. Has anyone any idea how I could use the username and password authentication check (the SQL) and start the session as well. Just in case you need to see the SQL, it is:

session_start(); ?>
<?php
$sql = &quot;SELECT ClientID, cpassword FROM clientinfo
WHERE ClientID='$ClientID'
AND cpassword='$Password'&quot;;

$result = mysql_query($sql)
or die(&quot;Error: MySQL said &quot;.mysql_error());
$num = mysql_num_rows($result);
$row = mysql_fetch_assoc($result);

if ($num == 1)
header(&quot;location: Logged In/WelcomeUserPage.php?&quot;);
?>
//THE CODE FOR THE FORM ETC.... COMES NEXT!!!!!!!!!!!!!!!!


Does any one have any ideas, its driving me crazy. Cheers for the help.
 
thats the problem I am having, if I remove this action from the form it validates the information with the database well, however it does not copy any information across, i.e. it doesnt print the clientID when saying &quot;welcome.....&quot; it just stays blank thus suggesting that the session doesnt perform. however if I use an action in the form, like I have done here, it loads up the session and says welcome CLIENT ID but doesnt cross check the details with the Database as expected so anyone can get in. The question is: as I have to remove the action in the form, the code does check the username and password with the DB and lets them in ONLY IF they match, but doesnt seem to copy the clientID accross thus defeating the object of sessions. Hope this is more understandable. Thanks!
 
A form must have an action attribute to be able to do anything.

Shouldn't the attribute, however, point back to this script, since this script contains the code to validate the input and set the session variable?

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Assume this is script1.php:
Code:
<?php
function show_form($value = '')
{
   print '<html>
   <body>
      <form method=&quot;POST&quot; action=&quot;script1.php&quot;>
         <input type=&quot;text&quot; name=&quot;the_number&quot; $value=&quot;' . $value . '&quot;>
         <input type=&quot;submit&quot;>
      </form>
   </body>
</html>';
}
      

session_start();

if (isset($_SESSION['number'])
{
   unset($_SESSION['number']);
}

$my_number = 4;

if (isset($_POST['the_number']))
{
   if ($_POST['the_number'] == $my_number)
   {
      $_SESSION['number'] = $my_number;
      header('Location: script2.php');
   }
   else
   {
      show_form ($_POST['the_number']);
   }
}
else
{
   show_form();
}
?>


Assume this is script2.php:
Code:
<?
session_start ();

if (isset($_SESSION['number']))
{
   print '<html><body>You're right!  The number was ' . $_SESSION['number'] . '!</body></html>';
}
else
{
   header ('Location: script1.php');
}
?>


When script1.php is first run by a user, there is no input -- no form with an input named &quot;the_number&quot; has been submitted. So all the script does is remove the session variable &quot;number&quot; (if it exists) and output a blank form and stop running. That blank form submits the data back to script1.php.

The browser renders the HTML output of script1.php and shows a web page to the user. the user fills out the entry and hits submit.

Script1.php runs again. This time, it gets input with an included field name of &quot;the_number&quot;, so it checks the value against what it's looking for.

If the input value matches, the script sets the session variable &quot;number&quot; and redirects the browser to script2.php. Script1.php stops running.

If the input does not match, the script outputs the form again, this time with the input field pre-populated with the previous number. Script1.php stops running. The browser renders the page, the user submits input, etc.

when a browser invokes script2.php, that script looks for the session variable &quot;number&quot;. If that session variable exists, it assumes the user correctly guessed the value the previous script was looking for.

If that session variable does not exist, script2.php redirects the browser to script1.php. This insures that script2.php can't be run before the user has run script1.php.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Yeah I think I follow that, but how does this differ to my script apart from the obvious where I use an SQL statement and here is using :

my_number = 4;

How do I call the SQL up so that it runs with the session on clicking submit, thus checking there details with the database and not with a given number like here (my_number = 4;) ???????????
 
Actually looking at my script on the logged in page, could it be the way I am calling the session variable up as I am doing this by including:

<?php
print &quot;<font color=\&quot;Black\&quot; size=\&quot;5\&quot;>
Home Page$Home_Page</font>&quot;;
print &quot;<br>&quot;;
print &quot;<br>Welome back <b>$ClientID</b>&quot;;
session_register('ClientID');
session_register('CDept');
// session_unregister('Home_Page');
// session_destroy();
?>

Which then brings up the message: Welcome back JBloggs (for example). When implementing this script (as created within this thread:

if (isset($_POST['ClientID']) and isset($_POST['Password']))
{
$sql = &quot;SELECT ClientID, cpassword FROM clientinfo WHERE ClientID='$ClientID' AND cpassword='$Password'&quot;;

$result = mysql_query($sql) or die(&quot;Error: MySQL said &quot;.mysql_error());

$num = mysql_num_rows($result);
$row = mysql_fetch_assoc($result);

$_SESSION['Home_Page']='Welcome back';

etc...

The code does appear to be using the sql and does Post to the new page but doesnt copy the ClientID over, well either that or this new code requires a different way of retrieving the data and I am typing it wrong. Cheers!
 
One last point, wouldnt it be necessary to use:

session_register('Home_Page');

Somewhere on the login page for this to work?
 
any ideas anyone? please!!!!!! thanks!
 
The $my_number = 4 replaces the entire MySQL connection section. Just assume that MySQL is always returning 4.


If you reference the elements of $_SESSION directly, it is not necessary to use session_register(). In fact, if you are referencing the elements of $_SESSION, the PHP online manual ( states that you should not use session_register().


In your logged-in page, where are you invoking session_start()?

Want the best answers? Ask the best questions: TANSTAAFL!!
 
With what web server are you using PHP?

There is a known issue with IIS in that when you use the &quot;Location:&quot; header, IIS does not allow cookies to be sent. This can cause problems with sessions, since they use cookies.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Its apache server. I understand that the $my_number = 4 replaces the entire MySQL connection section and it does seem to pick up the MySQL section now, and works fine. The area of it not working is posting the details across in the session to the next pages! It doesnt seem to run the session at all as no information can be retrieved on the other pages.
 
yep think so (towards bottom of code) code is now looking like this:

Sorry my code is as follows:

<?php
require_once('../Connections/MARTIN.php');
function output_form ($error_message = '', $ClientID = '')
{
print '<html>
<head>
<p align=&quot;center&quot;><title>HomePage</title>
<p align=&quot;center&quot;><meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot;>
</head>
<body>
<p align=&quot;center&quot;><img src=&quot;Sites%20Title%20Border.png&quot; width=&quot;799&quot; height=&quot;89&quot;></p>
<form method=&quot;POST&quot;
action = &quot; Logged In/WelcomeUserPage.php&quot;>
<p align=&quot;center&quot;><font color=&quot;Black&quot; size=&quot;5&quot;>Welcome to IT Help-OnLine</font><br><br><br>';
if ($error_message != '')
{
print '
<font color=red>' . $error_message . '</font>';
}

print '
<p align=&quot;center&quot;> <br>Please enter your <i>Client ID</i>,<i>Password</i> and select your <i>Department</i> below.
<br>
Client ID:<font color=&quot;#FFFFFF&quot;>::</font><input text type=&quot;text&quot; size=&quot;20&quot; maxlength=&quot;20&quot; name=&quot;ClientID&quot;';

if ($ClientID != '')
{
print ' value=&quot;' . $ClientID . '&quot;';
}

print '><br>
Password: <input text type=&quot;Password&quot; size&quot;15&quot; maxlength=&quot;20&quot; name=&quot;Password&quot; ><br>
<br>
</p>
<p align=&quot;center&quot;> Detpartment
<select name=&quot;CDept&quot; size=&quot;1&quot; id=&quot;CDept&quot;>
<option value=&quot;Unknown&quot;>Select</option>
<option value=&quot;Unknown&quot;>-----</option>
<option value=&quot;XRay&quot;>XRay</option>
<option value=&quot;Computing&quot;>Computing</option>
<option value=&quot;Renal&quot;>Renal</option>
<option value=&quot;Cardio&quot;>Cardio</option>
<option value=&quot;Heart Center&quot;>Heart Center</option>
<option value=&quot;Medical Health&quot;>Medical Health</option>
<option value=&quot;Diabetes&quot;>Diabetes</option>
<option value=&quot;Histology&quot;>Histology</option>
<option value=&quot;Ward 1-12&quot;>Ward 1-12</option>
<option value=&quot;Ward 13-20&quot;>Ward 13-20</option>
</select>
<br>
<br>
<input type = &quot;submit&quot; value=&quot;Click To Submit&quot;>
<input type = &quot;reset&quot; value=&quot;Reset&quot;>
</form>
<br>
<p align=&quot;Center&quot;>
If you are a new user please click <a href=&quot;New User Details/NewUserDetails.php&quot; target=&quot;_top&quot;>here</a>.
</p>
<p align=&quot;Center&quot;> Administrators log on <a href=&quot;Staff&Admin%20Login%20Page/Staff&Admin%20Login%20Page.php&quot;>here</a>
<br> <br> <br> <br>
<br>
<br>
<br>
<p><a href=&quot;mailto:jbloggs@hotmail.com&quot;>Email</a> us here</p>
</body>
</html>';
}
session_start();

mysql_select_db($database_MARTIN, $MARTIN);

if (isset($_POST['ClientID']) and isset($_POST['Password']))
{
$sql = &quot;SELECT ClientID, cpassword, CDept FROM clientinfo WHERE ClientID='$ClientID' AND cpassword='$Password' AND Cdept='$CDept'&quot;;

$result = mysql_query($sql) or die(&quot;Error: MySQL said &quot;.mysql_error());

$num = mysql_num_rows($result);
$row = mysql_fetch_assoc($result);

$_SESSION['Home_Page']='Welcome back';

if ($num != 0)
{
header(&quot;location: Logged In/WelcomeUserPage.php?&quot;);
}
else
{
output_form ('Your login was unsuccessful', $_POST['ClientID']);
}
}
else
{
output_form();
}
?>

Sorry this is turning into a long thread I am sure its close! Thanks!
 
Ok I removed the action from the form, as it will only work correctly with this I realise. I put the code in you suggested on the WelcomeUserPage and it came up with this:

Array ( )

 
The HTML spec requires that a form tag have an action attribute.


You want the user's input to be checked against the database by the script above. It must be checked by the script above for the session variable to ever possibly be set. Point the action attribute of the form produced by this script to the name of this script itself.

Look at the simpler code I posted yesterday. script1.php produces a form the action of which points back to script1.php.


Want the best answers? Ask the best questions: TANSTAAFL!!
 
I have created on my MySQL server in a database called &quot;test&quot; a table &quot;clientinfo&quot;, which contains:

Code:
+----------+-----------+-----------+
| ClientID | cpassword | CDept     |
+----------+-----------+-----------+
| fubar    | apass     | XRay      |
| snafu    | bpass     | Histology |
+----------+-----------+-----------+

I have created an include script MARTIN.php which reads:

Code:
<?php
$MARTIN = mysql_connect ('localhost', 'test', 'test') or die(mysql_error());

$database_MARTIN = 'test';
?>

I have created a login script named &quot;test_login.php&quot; which reads:

Code:
<?php
function output_form ($error_message = '', $ClientID = '')
{
   //The URL in the &quot;action&quot; attribute of the <form> tag below needs to be changed.
   print '<html>
   <head>
      <p align=&quot;center&quot;><title>HomePage</title>
      <p align=&quot;center&quot;><meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot;>
   </head>
   <body>
     <p align=&quot;center&quot;><img src=&quot;Sites%20Title%20Border.png&quot; width=&quot;799&quot; height=&quot;89&quot;></p>
      <form method=&quot;POST&quot; action=&quot;[URL unfurl="true"]http://10.0.1.133/test_login.php&quot;>[/URL]
       <p align=&quot;center&quot;><font color=&quot;Black&quot; size=&quot;5&quot;>Welcome to IT Help-OnLine</font><br><br><br>';
       
   
   if ($error_message != '')
   {
      print '
         <font color=red>' . $error_message . '</font>';
   }

   print '
       <p align=&quot;center&quot;>  <br>Please enter your <i>Client ID</i>,<i>Password</i> and select your <i>Department</i> below.
         <br>
         Client ID:<font color=&quot;#FFFFFF&quot;>::</font><input text type=&quot;text&quot; size=&quot;20&quot; maxlength=&quot;20&quot; name=&quot;ClientID&quot;';
   
   if ($ClientID != '')
   {
 print ' value=&quot;' . $ClientID . '&quot;';
   }
   
   print '><br>
         Password: <input text type=&quot;Password&quot; size&quot;15&quot; maxlength=&quot;20&quot; name=&quot;Password&quot; ><br>
            <br>
                  </p>
      <p align=&quot;center&quot;> Detpartment 
        <select name=&quot;CDept&quot; size=&quot;1&quot; id=&quot;CDept&quot;>
          <option value=&quot;Unknown&quot;>Select</option>
          <option value=&quot;Unknown&quot;>-----</option>
          <option value=&quot;XRay&quot;>XRay</option>
          <option value=&quot;Computing&quot;>Computing</option>
          <option value=&quot;Renal&quot;>Renal</option>
          <option value=&quot;Cardio&quot;>Cardio</option>
          <option value=&quot;Heart Center&quot;>Heart Center</option>
          <option value=&quot;Medical Health&quot;>Medical Health</option>
          <option value=&quot;Diabetes&quot;>Diabetes</option>
          <option value=&quot;Histology&quot;>Histology</option>
          <option value=&quot;Ward 1-12&quot;>Ward 1-12</option>
          <option value=&quot;Ward 13-20&quot;>Ward 13-20</option>
        </select>
        <br>
        <br>
         <input type = &quot;submit&quot; value=&quot;Click To Submit&quot;>
         <input type = &quot;reset&quot; value=&quot;Reset&quot;>
      </form>
      <br>
      <p align=&quot;Center&quot;>
       If you are a new user please click <a href=&quot;New User Details/NewUserDetails.php&quot; target=&quot;_top&quot;>here</a>.
      </p>
     <p align=&quot;Center&quot;> Administrators log on <a href=&quot;Staff&Admin%20Login%20Page/Staff&Admin%20Login%20Page.php&quot;>here</a> 
      <br> <br> <br> <br>
      <br>
      <br>
      <br>
      <p><a href=&quot;mailto:jbloggs@hotmail.com&quot;>Email</a> us here</p>
   </body>
</html>';
}


session_start();

require_once('MARTIN.php');   //this path needs to be changed

mysql_select_db($database_MARTIN, $MARTIN);

if (isset($_POST['ClientID']) and isset($_POST['Password']))
{
   $sql = &quot;SELECT ClientID, cpassword, CDept FROM clientinfo WHERE ClientID='$ClientID' AND cpassword='$Password' AND Cdept='$CDept'&quot;;

   $result = mysql_query($sql) or die(&quot;Error: MySQL said &quot;.mysql_error());

   $num = mysql_num_rows($result); 
   $row = mysql_fetch_assoc($result);

   $_SESSION['Home_Page']='Welcome back';
    
   if ($num != 0)
   {
   	//the URL in the &quot;Location&quot; HTTP header below needs to be changed.
      header(&quot;Location: [URL unfurl="true"]http://10.0.1.133/test_welcome.php&quot;);[/URL]
   }
   else
   {
      output_form ('Your login was unsuccessful', $_POST['ClientID']);
   }
}
else
{
   output_form();
}
?>

I have created a script named &quot;test_welcome.php&quot; which reads:

Code:
<?php
session_start();
print '<pre>';
print_r ($_SESSION);
?>


When I point my browser to test_login.php on my server (a LAMP (RH9/2.0.48/4.0.17/4.3.4) box), I get the login page.

When I enter user credentials that do not match a triplet in my database, I get the login page with the error message &quot;Your login was unsuccessful&quot;.

When I enter user credentials that do match a triplet in my database, I get the following:

Code:
Array
(
    [Home_Page] => Welcome back
)


For me, $_SESSION['Home_Page'] is being set correctly and is propogating to other pages in my URL.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Now you come to mention it I did try that earlier on, just did it again and it still comes up with the same thing if using:

print_r ($_SESSION);

It still comes up with: Array ( )

I have changed the action part of the form now to:

<p align=&quot;center&quot;><img src=&quot;Sites%20Title%20Border.png&quot; width=&quot;799&quot; height=&quot;89&quot;></p>
<form method=&quot;POST&quot;
action = &quot;
 
Are their session files in your server's temp directory? The directory is set by PHP's session.save_path directive. The files will begin with &quot;sess_&quot;.

Is there likely-looking information in your session store files?

Is your browser accepting cookies?

Want the best answers? Ask the best questions: TANSTAAFL!!
 
It is excepting cookies and working fine. remember I had it working previously when I submitted the action in the form to the next page, it then, for some reason uses the sessions perfectly, however it didnt use the SQL at all.

Now I have it using the SQL, but not the Sessions!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top