Jump to content

need help setting a session variable


webguync

Recommended Posts

I have a form where users enter name, username, password etc. The values are posted to a MySQL table where I also have a field called 'ID' that auto increments. I want to store that ID in a SESSION variable that I can carry over to other pages. Need help in doing this please.

Link to comment
Share on other sites

Provided the UserName is unique to the database, that seems like it would work.  However you need to actually execute the query.  Here's what it would look like:

 

$sql = "SELECT id, UserName, Password FROM Profile WHERE UserName='$user_name'";
$sql = mysql_query($sql) or die('Query Error: ' . mysql_error());
while ($row = mysql_fetch_assoc($sql)) {
    $_SESSION['id'] = $row['id'];
}

Link to comment
Share on other sites

do I have this right? It seems that the login doesn't work anymore. It worked before adding the while loop.

<?php session_start();



//Connect to database from here

$link = mysql_connect('localhost', 'uname', 'pw'); 

if (!$link) {

    die('Could not connect: ' . mysql_error());

}

//select the database | Change the name of database from here

mysql_select_db('DB_Name'); 



//get the posted values

$user_name=htmlspecialchars($_POST['UserName'],ENT_QUOTES);

$pass=md5($_POST['Password']);



//now validating the username and password

$sql="SELECT id,UserName, Password FROM Profile WHERE UserName='".$user_name."'";

$result=mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
    $_SESSION['id'] = $row['id'];
}



//if username exists

if(mysql_num_rows($result)>0)

{

//compare the password

if(strcmp($row['Password'],$pass)==0)

{

	echo "<h3>Success! </h3>";

	//now set the session from here if needed
	$_SESSION['id']=$id; 

	$_SESSION['UserName']=$user_name; 

	//file upload

	echo "

	<form enctype='multipart/form-data' action='flash_upload.php' method='POST'>

    <fieldset>

    <legend>Upload your profile picture</legend>

    <ol>

      <li id='example3'>

        <label for='FileUpload'>Choose a file to upload:</label>

        <input name='myfile' id='FileUpload'  type='file' />
	 <input type='submit' name='submit' value='Upload File' />

      </li>

    </ol>

    </fieldset>

   

  </form>

  ";

}

else

	echo "<H3>invalid login credentials</h3>"; 

}

else

echo "<h3>invalid login credentials</h3>"; //Invalid Login





?>

Link to comment
Share on other sites

On face value I don't see anything wrong with your code, but to clean up some of the logic, you should change your SQL query to

 

$sql="SELECT id, UserName, Password FROM Profile WHERE UserName='$user_name' AND Password='$pass'";

 

^ When using double quotes you can use a variable inside the string; you don't have to concatinate.  Read below for the logic:

 

while ($row = mysql_fetch_assoc($result)) {
    // If we even get this far, that means the username and password have already been validated
    // by the database...there's no need for "if(mysql_num_rows($result)>0)" or "if(strcmp($row['Password'],$pass)==0)"
    $_SESSION['id'] = $row['id'];
    $_SESSION['UserName']=$user_name;
}

// After the query, check to see if the $_SESSION['id'] is set.  If it is, you know the user was logged in successfully.

 

This means that the ONLY time you should create a $_SESSION['id'] variable is when you have successfully retrieved a row from the database on login.  At the beginning of each script, check for the session id; for a log-out script, simply unset the session id variable.

Link to comment
Share on other sites

thanks.

 

taking out the current if statements

//if username exists

if(mysql_num_rows($result)>0)

{

//compare the password

if(strcmp($row['Password'],$pass)==0)

{

	echo "<h3>Success! </h3>";

	//now set the session from here if needed
	$_SESSION['id']=$id; 

	$_SESSION['UserName']=$user_name; 

	//file upload

	echo "

	<form enctype='multipart/form-data' action='flash_upload.php' method='POST'>

    <fieldset>

    <legend>Upload your profile picture</legend>

    <ol>

      <li id='example3'>

        <label for='FileUpload'>Choose a file to upload:</label>

        <input name='myfile' id='FileUpload'  type='file' />
	 <input type='submit' name='submit' value='Upload File' />

      </li>

    </ol>

    </fieldset>

   

  </form>

  ";

}

else

	echo "<H3>invalid login credentials</h3>"; 

}

else

echo "<h3>invalid login credentials</h3>"; //Invalid Login





?>


 

how would I handle the success and failure echos?

Link to comment
Share on other sites

do I have this right now? It isn't evaluating a success when it should be.

 

<?php session_start();



//Connect to database from here

$link = mysql_connect('localhost', 'uname', 'pw'); 

if (!$link) {

    die('Could not connect: ' . mysql_error());

}

//select the database | Change the name of database from here

mysql_select_db('DBName'); 



//get the posted values

$user_name=htmlspecialchars($_POST['UserName'],ENT_QUOTES);

$pass=md5($_POST['Password']);



//now validating the username and password

$sql="SELECT id,UserName, Password FROM Profile WHERE UserName='$user_name.' AND Password='$pass'";

$result=mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
    $_SESSION['id'] = $row['id'];
$_SESSION['UserName']=$user_name; 
}
if(isset($_SESSION['id']))
   
  {

	echo "<h3>Success! </h3>";



	//file upload

	echo "

	<form enctype='multipart/form-data' action='flash_upload.php' method='POST'>

    <fieldset>

    <legend>Upload your profile picture</legend>

    <ol>

      <li id='example3'>

        <label for='FileUpload'>Choose a file to upload:</label>

        <input name='myfile' id='FileUpload'  type='file' />
	 <input type='submit' name='submit' value='Upload File' />

      </li>

    </ol>

    </fieldset>

   

  </form>

  ";

  }
  





else
{

	echo "<H3>invalid login credentials</h3>"; 


  }






?>

Link to comment
Share on other sites

Your query is probably returning an empty result set, but since you aren't checking for that condition with mysql_num_rows(), you wouldn't know.

 

Why are you doing this? It's wholly unnecessary; you should be using mysql_real_escape_string().

$user_name=htmlspecialchars($_POST['UserName'],ENT_QUOTES);

Link to comment
Share on other sites

I changed my code to this to debug and I create a username/pw and login with those credentials and it returns a 0 for num row. s/b returning 1. So I know my code isn't working, but still need to know why, since it s/b working.

 

<?php session_start();



//Connect to database from here

$link = mysql_connect('localhost', 'uname', 'pw'); 

if (!$link) {

    die('Could not connect: ' . mysql_error());

}

//select the database | Change the name of database from here

mysql_select_db('DBName'); 



//get the posted values

$user_name=mysql_real_escape_string($_POST['UserName']);

$pass=md5($_POST['Password']);



//now validating the username and password

$sql="SELECT id,UserName,Password FROM Profile WHERE UserName='$user_name.' AND Password='$pass'";

$result=mysql_query($sql);
echo mysql_num_rows($result);


while ($row = mysql_fetch_assoc($result)) {
    $_SESSION['id'] = $row['id'];
$_SESSION['UserName']=$user_name; 
}
if(isset($_SESSION['id']))
   
  {

	echo "<h3>Success! </h3>";



	//file upload

	echo "

	<form enctype='multipart/form-data' action='flash_upload.php' method='POST'>

    <fieldset>

    <legend>Upload your profile picture</legend>

    <ol>

      <li id='example3'>

        <label for='FileUpload'>Choose a file to upload:</label>

        <input name='myfile' id='FileUpload'  type='file' />
	 <input type='submit' name='submit' value='Upload File' />

      </li>

    </ol>

    </fieldset>

   

  </form>

  ";

  }
  





else
{

	echo "<H3>invalid login credentials</h3>"; 


  }






?>

Link to comment
Share on other sites

You need to log into your database manually and check out what values are stored in the row you want to retrieve.  Echo the variables you get from POST and see where the difference lies.  I'm guessing it could have something to do with escape slashes or something.

 

Checking the 'affected rows' isn't necessary in this case as that is what the session variable check is for.  If the session variable isn't set, that's because now rows were returned.

Link to comment
Share on other sites

thanks for the help so far. I figured out there was an extra period in my SQL statement, so taking that out fixed the login problem. Still need to figure out one more thing though. After they login successfully, they see a form to upload a file. I want to update the Profile table info with the path to the file in a field in MySQL called 'Path_to_File'. This part isn't working. I am probably doing something wrong with the stored ID SESSION var.

 

Here is my code to produce that part.



<?php

ini_set("display_errors","1");

ERROR_REPORTING(E_ALL);



$db_user = "uname";

$db_pass = "pw";

$db = "DBName";





$link = mysql_connect('localhost',$db_user,$db_pass);

$db_selected = mysql_select_db($db);

/*debugging*/



if (!$link) {

    die('Could not connect: ' . mysql_error());

}

echo 'Connected successfully';



if (!$db_selected) {

    die ('Can\'t use foo : ' . mysql_error());

}


$_SESSION['id'] = $row['id'];
$uploadDir = dirname(__FILE__) . '/files/';

$uploadFile = $uploadDir . basename($_FILES['myfile']['name']);

//Print_r ($_FILES);



if ($_POST['submit'] != '') {

    // 1. submitting the html form

    if (!isset($_GET['jqUploader'])) {

        // 1.a javascript off, we need to upload the file

        if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {

	 $statement = "UPDATE `Profile` SET `Path_to_File` = '$value' WHERE `user_id` = {$_SESSION['id']}";

                echo "<P>".$statement;

                mysql_query($statement);

                echo "<P>".mysql_error();

            // delete the file

            // @unlink ($uploadFile);

            $html_body = '<h1>File successfully uploaded!</h1><pre>';

            $html_body .= print_r($_FILES, true);

            $html_body .= '</pre>';

        } else {

            $html_body = '<h1>File upload error!</h1>';



            switch ($_FILES['myfile']['error']) {

                case 1:

                    $html_body .= 'The file is bigger than this PHP installation allows';

                    break;

                case 2:

                    $html_body .= 'The file is bigger than this form allows';

                    break;

                case 3:

                    $html_body .= 'Only part of the file was uploaded';

                    break;

                case 4:

                    $html_body .= 'No file was uploaded';

                    break;

                default:

                    $html_body .= 'unknown errror';

            }

            $html_body .= 'File data received: <pre>';

            $html_body .= print_r($_FILES, true);

            $html_body .= '</pre>';

        }

        $html_body = '<h1>Results</h1><pre>';

        $html_body .= print_r($_POST, true);

        $html_body .= '</pre>';

    } else {

        // 1.b javascript on, so the file has been uploaded and its filename is in the POST array

        $html_body = '<h1>Form posted!</h1><p>Error:<pre>';

        $html_body .= print_r($_POST, false);

        $html_body .= '</pre>';

    }

    myHtml($html_body);

} else {

    if ($_GET['jqUploader'] == 1) {

        // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        // 2. performing jqUploader flash upload



        if ($_FILES['myfile']['name']) {

          if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {

                $statement = "UPDATE `Profile` SET `Path_to_File` = '$value' WHERE `user_id` = {$_SESSION['id']}";

             echo "<P>".$statement;

             mysql_query($statement);

               echo "<P>".mysql_error();

                 //delete the file

                  //@unlink ($uploadFile);

                return $uploadFile;

            }

        } else {

            if ($_FILES['myfile']['error']) {

                return $_FILES['myfile']['error'];

            }

        }

    }

}

// /////////////////// HELPER FUNCTIONS

function myHtml($bodyHtml)

{



    ?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<html lang="en">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>File Upload</title>

<link rel="stylesheet" type="text/css" media="screen" href="style.css"/>

</head>

<body>

<?php echo $bodyHtml;



    ?>

</body>

</html>

<?php

}



?>



 

and form upload file code

 

<form enctype='multipart/form-data' action='Profile.php' method='POST'>

    <fieldset>

    <legend>Upload your profile picture</legend>

    <ol>

      <li id='example3'>

        <label for='FileUpload'>Choose a file to upload:</label>

        <input name='myfile' id='FileUpload'  type='file' />
	 <input type='submit' name='submit' value='Upload File' />

      </li>

    </ol>

    </fieldset>

   

  </form>


Link to comment
Share on other sites

spoke too soon about the login working b/c any login will resolve to a Success. Something is amiss with my Else statement. Any ideas?

 

<?php session_start();



//Connect to database from here

$link = mysql_connect('localhost', 'uname', 'pw'); 

if (!$link) {

    die('Could not connect: ' . mysql_error());

}

//select the database | Change the name of database from here

mysql_select_db('DBName'); 



//get the posted values

$user_name=mysql_real_escape_string($_POST['UserName']);

$pass=md5($_POST['Password']);



//now validating the username and password

$sql="SELECT id,UserName,Password FROM Profile WHERE UserName='$user_name' AND Password='$pass'";

$result=mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    $_SESSION['id'] = $row['id'];
$_SESSION['UserName']=$user_name; 
}
//echo ($sql);



if(isset($_SESSION['id']))
   
  {

	echo "<h3>Success! </h3>";



	//file upload

	echo "

	<form enctype='multipart/form-data' action='Profile.php' method='POST'>

    <fieldset>

    <legend>Upload your profile picture</legend>

    <ol>

      <li id='example3'>

        <label for='FileUpload'>Choose a file to upload:</label>

        <input name='myfile' id='FileUpload'  type='file' />
	 <input type='submit' name='submit' value='Upload File' />

      </li>

    </ol>

    </fieldset>

   

  </form>

  ";

  }
  





else
{

	echo "<h3>invalid login credentials</h3>"; 
	echo "<h4>Please go <a href='login.php'>Back</a> and try again!</h4>";


  }






?>

Link to comment
Share on other sites

Are you sure about the login not working?  You are using session variables after all.  To test that, unset all your session login variables after the script (don't keep them in after this goes public though).

 

UPDATE `Profile` SET `Path_to_File` = '$value'

 

Why do you use $value?  I don't see that anywhere else in your script.

Link to comment
Share on other sites

I am trying the login from another computer and it seems to work, so maybe it was a Session thing. As for the file upload, I changed my SQL to this/

 

$statement = "UPDATE `Profile` SET `Path_to_File` = '$uploadFile' WHERE `user_id` = {$_SESSION['id']}";

 

but I still get the errors.

 

Notice: Undefined variable: row in /Profile.php on line 46

UPDATE `Profile` SET `Path_to_File` = '//files/526859298_bca55ad8ca.jpg' WHERE `user_id` =

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 

Link to comment
Share on other sites

What is this "id" being used for?  Are you trying to retrieve the user's unique ID from the database after they've signed up?  If so, after your first SQL query that inputs the username/password into the database you need to run another query to retrieve the ID.  Please show me all the code that's pertinent to what you're trying to do.

Link to comment
Share on other sites

probably has something to do  with the id session variable not holding.

 

Here is the code that processes the login and if login is successful, displays a form to upload a file.

 

<?php session_start();



//Connect to database from here

$link = mysql_connect('localhost', 'uname', 'pw'); 

if (!$link) {

    die('Could not connect: ' . mysql_error());

}

//select the database | Change the name of database from here

mysql_select_db('DBName'); 



//get the posted values

$user_name=mysql_real_escape_string($_POST['UserName']);

$pass=md5($_POST['Password']);


//now validating the username and password

$sql="SELECT id,UserName,Password FROM Profile WHERE UserName='$user_name' AND Password='$pass'";

$result=mysql_query($sql);
//echo ($sql);
while ($row = mysql_fetch_assoc($result)) {
    $_SESSION['id'] = $row['id'];
$_SESSION['UserName']=$user_name; 
}


if(isset($_SESSION['id']))
   
  {

	echo "<h3>Success! </h3>";
	echo "<h3>Welcome " . $_SESSION['UserName'] . "</h3>";
	echo "<h4><a href='logout.php'>logout</a></h4>";



	//file upload

	echo "

	<form enctype='multipart/form-data' action='Profile.php' method='POST'>

    <fieldset>

    <legend>Upload your profile picture</legend>

    <ol>

      <li id='example3'>

        <label for='FileUpload'>Choose a file to upload:</label>

        <input name='myfile' id='FileUpload'  type='file' />
	 <input type='submit' name='submit' value='Upload File' />

      </li>

    </ol>

    </fieldset>

   

  </form>

  ";

  }
  





else
{

	echo "<h3>invalid login credentials</h3>"; 
	echo "<h4>Please go <a href='login.php'>Back</a> and try again!</h4>";


  }






?>

 

and the code to process the file upload

<?php
session_start();
//print_r($_SESSION);
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];



$db_user = "uname";

$db_pass = "pw";

$db = "DBName";





$link = mysql_connect('localhost',$db_user,$db_pass);

$db_selected = mysql_select_db($db);

/*debugging*/



if (!$link) {

    die('Could not connect: ' . mysql_error());

}

//echo 'Connected successfully';



if (!$db_selected) {

    die ('Can\'t use foo : ' . mysql_error());

}


//$_SESSION['id'] = ['id'];
$uploadDir = dirname(__FILE__) . '/files/';

$uploadFile = $uploadDir . basename($_FILES['myfile']['name']);

//Print_r ($_FILES);



if ($_POST['submit'] != '') {

    // 1. submitting the html form

    if (!isset($_GET['jqUploader'])) {

        // 1.a javascript off, we need to upload the file

        if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {

	 $statement = "UPDATE Profile SET Path_to_File='$uploadFile' WHERE id='{$_SESSION['id']}'";

                echo "<p> File successfully uploaded</p>";
			echo"<p><a href='logout.php'>Logout</a></p>";

              

            // delete the file

            // @unlink ($uploadFile);

            $html_body = '<h1>File successfully uploaded!</h1><pre>';

            //$html_body .= print_r($_FILES, true);

            $html_body .= '</pre>';

        } else {

            $html_body = '<h1>File upload error!</h1>';



            switch ($_FILES['myfile']['error']) {

                case 1:

                    $html_body .= 'The file is bigger than this PHP installation allows';

                    break;

                case 2:

                    $html_body .= 'The file is bigger than this form allows';

                    break;

                case 3:

                    $html_body .= 'Only part of the file was uploaded';

                    break;

                case 4:

                    $html_body .= 'No file was uploaded';

                    break;

                default:

                    $html_body .= 'unknown errror';

            }

            $html_body .= 'File data received: <pre>';

            $html_body .= print_r($_FILES, true);

            $html_body .= '</pre>';

        }

        $html_body = '<h1>Results</h1><pre>';

        $html_body .= print_r($_POST, true);

        $html_body .= '</pre>';

    } else {

        // 1.b javascript on, so the file has been uploaded and its filename is in the POST array

        $html_body = '<h1>Form posted!</h1><p>Error:<pre>';

        $html_body .= print_r($_POST, false);

        $html_body .= '</pre>';

    }

    //myHtml($html_body);

} else {

    if ($_GET['jqUploader'] == 1) {

        // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        // 2. performing jqUploader flash upload



        if ($_FILES['myfile']['name']) {

          if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {

                $statement = "UPDATE Profile SET Path_to_File='$uploadFile' WHERE id='{$_SESSION['id']}'";

             /*echo "<P>".$statement;

             mysql_query($statement);

               echo "<P>".mysql_error();
		   */

                 //delete the file

                  //@unlink ($uploadFile);

                return $uploadFile;

            }

        } else {

            if ($_FILES['myfile']['error']) {

                return $_FILES['myfile']['error'];

            }

        }

    }

}




    ?>

 

the uploading of files into the 'files' directory seems to work, just not the posting into the Profile table in the database.

Link to comment
Share on other sites

After this IF statement:

if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {

Try and echo something simple like "WTF" as well as the sql query just so you can figure out if the IF statement is working.  Also, why have you commented out the mysql_query() function; that's what actually executes the query.

 

On a side note, are you using a good editor for your scripts?  One with color coding?  I use Notepad++.  If you're just using something like regular notepad then it becomes much more difficult to spot errors in syntax.  Also, try and find ways of formatting your script so it's easier to read.  For example:

 

Change

if (!$link) {

    die('Could not connect: ' . mysql_error());

}

To

if (!link) die('Could not connect: ' . mysql_error());

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.