Session username and mySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Terencentanio
Forum Commoner
Posts: 27
Joined: Mon Dec 06, 2004 10:32 am
Location: England

Session username and mySQL

Post by Terencentanio »

Yo.

I'm trying to make a script that when submitted, takes the user session name and their submitted info and inserts it into a DB.

The code is:

Code: Select all

$requesting=$_POSTї'stocks'];
$payment=$_POSTї'payment'];
$buyer=$_SESSIONї'username'];

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$query = "INSERT INTO requests VALUES ('','$buyer','$requesting')";
mysql_query($query);
... I can't see anything wrong with it, but as it is the "buyer" field of the DB is just blank and if I add "." or "'." or whatever, I just get mass errors.

Can someone help, please? Maybe tell me another way of getting a session name? Thanks.

[EDIT]

The mySQL fields are "ID, buyer, request" in that order... so the SQL IS " '','$buyer','$requesting' "
Last edited by Terencentanio on Thu Dec 09, 2004 4:57 pm, edited 1 time in total.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Where do you assign the session variable? Can you post the code?

Also, don't forget your quotes on 'localhost' :wink:

If you're a bit baffled post back and say so. You'll get plenty of help :-D

EDIT: I prefer to use this query too

Code: Select all

$query = 'INSERT INTO `requests` (id,buyer,requests) VALUES ('','$buyer','$requesting');
It's a bit clearer where your values are going that way. Especially when you start using large databases ;-)
Last edited by Chris Corbyn on Thu Dec 09, 2004 5:02 pm, edited 1 time in total.
Terencentanio
Forum Commoner
Posts: 27
Joined: Mon Dec 06, 2004 10:32 am
Location: England

Post by Terencentanio »

The code has never needed quotes on local host before and it's worked fine.

Um..

[EDIT]

Sorry.. just checked.

Code: Select all

<input type="hidden" value="<?php echo $_SESSION&#1111;'username'] ?>" name="buyer">
<input type="hidden" value="1" name="payment">
<input type="submit" name="" value="Purchase">
That's if I use $_POST instead of $_SESSION (instead of getting it on that page, I tried to send it from the other)

... the whole block is:

Code: Select all

<?php

require 'db_connect.php';

if ($logged_in == 0) &#123;
        die('<B><font face=verdana size=2 color=000000>You need to be <a href=login.php>logged in.</A></B>');
&#125;

$db_object->disconnect();

$username="--";
$password="--";
$database="--";

$requesting=$_POST&#1111;'stocks'];
$payment=$_POST&#1111;'payment'];
$buyer=$_POST&#1111;'buyer'];

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$query = "INSERT INTO requests VALUES ('','$buyer','$requesting')";
mysql_query($query);

mysql_close();
?>
That's the code to connect to the login checker file and the code I use to insert teh info.
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post by rehfeld »

Terencentanio wrote:The code has never needed quotes on local host before and it's worked fine.

Um..

yes it works, but its bad practive not to use quotes

try putting
error_reporting(E_ALL);

at the top of your script and you will see

again though, like said above, does $_SESSION['username'] even exist?
does it contain a value?
have you made sure?
Terencentanio
Forum Commoner
Posts: 27
Joined: Mon Dec 06, 2004 10:32 am
Location: England

Post by Terencentanio »

Well, if I add

Code: Select all

<?php echo $_SESSION&#1111;'username']; ?>
... to the page, it is blank on first load but if I refresh it appears, then another refresh and it goes, etc.

There're 2 pages, one is check_login.php which handles username and password sessions, the other is db_connect.php which connects to the database and includes check_login.php
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

You need to assign a value to $_SESSION['username']

In other words it has to be at the left hand side of " = " somewhere in your code.

If you're going to use sessions always put

Code: Select all

<?php session_start(); ?>
right at the VERY TOP of the page before anything else in the document.

And to assign each variable you do this

Code: Select all

$_SESSION['username'] = 'Username of user';
So if it was sent from a form field called "username" this code does it in the page the form is sent to

Code: Select all

$username = $_POST['username'];

$_SESSION['username'] = $username;

// or simply $_SESSION['username'] = $_POST['username'];
But it will not work at all if session_start(); isn't right at the top.

To pass the variable between pages just put

Code: Select all

?'.SID.' //means "Session ID"
in the URL and then remember to put session_start(); at the top of the other page ;-)

eg.

Code: Select all

echo '<a href="somelink.php?'.SID.'&otherstuff=something_else">Link here</a>';
Terencentanio
Forum Commoner
Posts: 27
Joined: Mon Dec 06, 2004 10:32 am
Location: England

Post by Terencentanio »

Ereet. Thanks for that.

I just don't understand why it doesn't already have a value.

This is how teh system works:

user goes to register.php and creates an account
user goes to login.php and logs in using their password and username
every page except login.php and register.php checks that they're logged in and if not, doesn't load the page.

Shouldn't this mean that the session username and password already has values? :S
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

This code will pass the word "Bonkers!" stored as a session variable called "scripter" between page1.php and page2.php

in page1.php

Code: Select all

<?php

session_start();

$_SESSION['scripter'] = 'Bonkers!';

?>

<html>
<head>
<title>
Page 1 
</title>
</head>
<body>
<?php echo '<a href="page2.php?'.SID.'">Click me!</a>'; ?>
</body>
</html>
and in page2.php...

Code: Select all

<?php

session_start();

?>

<html>
<head>
<title>
Page 2
</title>
</head>
<body>
<?php echo 'Your session variable is '.$_SESSION["scripter"]; ?>
</body>
</html>
Hope this helps ;-)
Terencentanio
Forum Commoner
Posts: 27
Joined: Mon Dec 06, 2004 10:32 am
Location: England

Post by Terencentanio »

Woa, woa. I think I found a possible problem. I reassigned "buyer" to a different value (bollocks, to be exact) and it still didn't insert into teh DB :S
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Yup but you need session_start(); at the top of the code in the page you're using to query your database and SID in the URL that points to it
Terencentanio
Forum Commoner
Posts: 27
Joined: Mon Dec 06, 2004 10:32 am
Location: England

Post by Terencentanio »

Screw it. I changed some stuff and it did insert "bollocks" into the DB. I'm gonna keep messing with it and hopefully something will come out.

Thanks, doods.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Don't matter if they're long do this...

Post the code in login.php, register.php, and the full page that first bit of code came from and I'll let you know what the problem is ;-)
Terencentanio
Forum Commoner
Posts: 27
Joined: Mon Dec 06, 2004 10:32 am
Location: England

Post by Terencentanio »

register.php

Code: Select all

<?php
require('db_connect.php');        // database connect script.
?>
<?php

if (isset($_POST&#1111;'submit'])) &#123; // if form has been submitted
      /* check they arent ripping you off */
	  
	  $first_buy = $_POST&#1111;'first_shares'];

if($first_buy<4)
header ("Location: register.php");
	  
	  /* check they filled in what they supposed to,
        passwords matched, username
        isn't already taken, etc. */

        if (!$_POST&#1111;'uname'] | !$_POST&#1111;'passwd'] | !$_POST&#1111;'passwd_again'] | !$_POST&#1111;'email']) &#123;
                die('You missed something');
        &#125;

        // check if username exists in database.

        if (!get_magic_quotes_gpc()) &#123;
                $_POST&#1111;'uname'] = addslashes($_POST&#1111;'uname']);
        &#125;



        $name_check = $db_object->query("SELECT username FROM users WHERE username = '".$_POST&#1111;'uname']."'");

        if (DB::isError($name_check)) &#123;
                die($name_check->getMessage());
        &#125;

        $name_checkk = $name_check->numRows();

        if ($name_checkk != 0) &#123;
                die('Sorry, the username: <strong>'.$_POST&#1111;'uname'].'</strong> is already taken, please pick another one.');
        &#125;

        // check passwords match

        if ($_POST&#1111;'passwd'] != $_POST&#1111;'passwd_again']) &#123;
                die('Passwords did not match.');
        &#125;

        // check e-mail format

        if (!preg_match("/.*@.*..*/", $_POST&#1111;'email']) | preg_match("/(<|>)/", $_POST&#1111;'email'])) &#123;
                die('Invalid e-mail address.');
        &#125;

        // no HTML tags in username, website, location, password

        $_POST&#1111;'uname'] = strip_tags($_POST&#1111;'uname']);
        $_POST&#1111;'passwd'] = strip_tags($_POST&#1111;'passwd']);
        $_POST&#1111;'website'] = strip_tags($_POST&#1111;'website']);
        $_POST&#1111;'location'] = strip_tags($_POST&#1111;'location']);



        // check show_email data

        if ($_POST&#1111;'show_email'] != 0 & $_POST&#1111;'show_email'] != 1) &#123;
                die('Nope');
        &#125;

        // now we can add them to the database.
        // encrypt password

        $_POST&#1111;'passwd'] = md5($_POST&#1111;'passwd']);

        if (!get_magic_quotes_gpc()) &#123;
                $_POST&#1111;'passwd'] = addslashes($_POST&#1111;'passwd']);
                $_POST&#1111;'email'] = addslashes($_POST&#1111;'email']);
                $_POST&#1111;'website'] = addslashes($_POST&#1111;'website']);
                $_POST&#1111;'location'] = addslashes($_POST&#1111;'location']);
        &#125;



        $regdate = date('m d, Y');

        $insert = "INSERT INTO users (
                        username,
                        password,
                        regdate,
                        email,
                        website,
                        location,
                        show_email,
                        last_login)
                        VALUES (
                        '".$_POST&#1111;'uname']."',
                        '".$_POST&#1111;'passwd']."',
                        '$regdate',
                        '".$_POST&#1111;'email']."',
                        '".$_POST&#1111;'website']."',
                        '".$_POST&#1111;'location']."',
                        '".$_POST&#1111;'show_email']."',
                        'Never')";

        $add_member = $db_object->query($insert);

        if (DB::isError($add_member)) &#123;
                die($add_member->getMessage());
        &#125;

        $db_object->disconnect();
		
$username="---";
$password="---";
$database="---";

$payment=$_POST&#1111;'payment'];
$requesting=$_POST&#1111;'first_shares'];
$value=$_POST&#1111;'value'];
$compliment=$_POST&#1111;'compliment'];

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$query = "UPDATE users SET stocks = '$compliment' WHERE username = '".$_POST&#1111;'uname']."'";
mysql_query($query);

$query2 = "UPDATE users SET payment = '$payment' WHERE username = '".$_POST&#1111;'uname']."'";
mysql_query($query2);

$query3 = "UPDATE users SET value = '$value' WHERE username = '".$_POST&#1111;'uname']."'";
mysql_query($query3);

$query4 = "UPDATE users SET requesting = '$requesting' WHERE username = '".$_POST&#1111;'uname']."'";
mysql_query($query4);
		
?>
<html>
<head>
<title>Root32Shares</title>
<script type="text/javascript" language="JavaScript1.2" src="stm31.js"></script>
<style type="text/css">
<!--
A:link &#123; COLOR: 08475C; TEXT-DECORATION: none; font-weight: normal &#125;
A:visited &#123; COLOR: 08475C; TEXT-DECORATION: none; font-weight: normal &#125;
A:active &#123; COLOR: 08475C; TEXT-DECORATION: none &#125;
A:hover &#123; COLOR: 0B6988; TEXT-DECORATION: none; font-weight: normal &#125;
-->
</style>
<style type="text/css">
a:link &#123;text-decoration: none&#125;
a:active &#123;text-decoration: none&#125;
a:visited &#123;text-decoration: none&#125;
a:hover &#123;text-decoration: none&#125;
</style>
</head>
<body bgcolor=#ffffff text=#000000 marginwidth=0 marginheight=0 leftmargin=0 rightmargin=0 bottommargin=0 topmargin=0">
<BR>
<table cellpadding="0" cellspacing="1" bgcolor="000000" align="center" width="600">
<tr>
<td bgcolor="0B6988">
<CENTER>
<img src="banner.jpg"></CENTER></td>
</tr>
<tr>
<td bgcolor="eeeef0">
<BR>
<font face="verdana" size="2" color="000000">                
<table cellpadding="5" cellspacing="0" bgcolor="FFFFFF" align="center">
<tr>
<td bgcolor="eeeef0">
<font face="verdana" size="2" color="000000">  
Your account has been created. You have <B><?php echo $_POST&#1111;'first_shares']; ?></B> stock and a complimentary <B>1</B> stock.<BR><BR>

Thanks for your interest! You can login <a href="login.php">here</A>
</td>
</tr>
</table>
<BR>
</td>
</tr>
</table>
<BR>
<CENTER><font face="verdana" size="1" color="666666">
&copy; Copyright, 2004 - Root32<BR>
| <a href="mailto:masters@root32mail.com">contact</a> | <a href="http://root32.com">root32 computing and security</A> | <a href="http://root32.info">root32 hosting</A> | <a href="http://root32mail.com">root32 mail</A> |

<BR>

<?php

&#125; else &#123;        // if form hasn't been submitted

?>
<html>
<head>
<title>Root32Shares</title>
<script type="text/javascript" language="JavaScript1.2" src="stm31.js"></script>
<style type="text/css">
<!--
A:link &#123; COLOR: 08475C; TEXT-DECORATION: none; font-weight: normal &#125;
A:visited &#123; COLOR: 08475C; TEXT-DECORATION: none; font-weight: normal &#125;
A:active &#123; COLOR: 08475C; TEXT-DECORATION: none &#125;
A:hover &#123; COLOR: 0B6988; TEXT-DECORATION: none; font-weight: normal &#125;
-->
</style>
<style type="text/css">
a:link &#123;text-decoration: none&#125;
a:active &#123;text-decoration: none&#125;
a:visited &#123;text-decoration: none&#125;
a:hover &#123;text-decoration: none&#125;
</style>
</head>
<body bgcolor=#ffffff text=#000000 marginwidth=0 marginheight=0 leftmargin=0 rightmargin=0 bottommargin=0 topmargin=0">
<BR>

<table cellpadding="0" cellspacing="1" bgcolor="000000" align="center" width="600">
<tr>
<td bgcolor="0B6988">
<CENTER>
<img src="banner.jpg"></CENTER></td>
</tr>
<tr>
<td bgcolor="eeeef0">
<BR>
<form action="<?php echo $_SERVER&#1111;'PHP_SELF']; ?>" method="post">
<table align="center" cellpadding="5">
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> Username*:</td><td bgcolor="eeeef0">
<input type="text" name="uname" maxlength="40">
</td></tr>
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> Password*:</td><td bgcolor="eeeef0">
<input type="password" name="passwd" maxlength="50">
</td></tr>
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> Confirm Password*:</td><td bgcolor="eeeef0">
<input type="password" name="passwd_again" maxlength="50">
</td></tr>
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> E-Mail*:</td><td bgcolor="eeeef0">
<input type="text" name="email" maxlength="100">
</td></tr>
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> Website:</td><td bgcolor="eeeef0">
<input type="text" name="website" maxlength="150">
</td></tr>
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> Location</td><td bgcolor="eeeef0">
<input type="text" name="location" maxlength="150">
</td></tr>
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> Show E-Mail?</td><td bgcolor="eeeef0">
<select name="show_email">
<option value="1" selected="selected">Yes</option>
<option value="0">No</option></select>
</td></tr>
<tr><td bgcolor="eeeef0"><font face="Verdana" color="000000" size="2"><B> Stocks:</td><td bgcolor="eeeef0">
<input type="text" name="first_shares" maxlength="3" value="5" size="5"> <font face="Verdana" color="000000" size="2"> (£1 each)
</td></tr>
<tr><td align="center" colspan="2"><center><font face="verdana" size="1">* You must purchase at least 5 stocks when signing up. Stocks are £1 each. *
</td>
</tr>
<tr><td colspan="2" align="center" bgcolor="eeeef0">
<input type="hidden" value="1" name="payment">
<input type="hidden" value="71000" name="value">
<input type="hidden" value="1" name="compliment">
<input type="submit" name="submit" value="Sign Up">
</td></tr>
</table>
</form>
</td>
</tr>
</table>
<BR>
<CENTER><font face="verdana" size="1" color="666666">
&copy; Copyright, 2004 - Root32<BR>
| <a href="mailto:masters@root32mail.com">contact</a> | <a href="http://root32.com">root32 computing and security</A> | <a href="http://root32.info">root32 hosting</A> | <a href="http://root32mail.com">root32 mail</A> |

</body>
</html>
<BR><BR>
<?php

&#125;

?>
</body>
</html>
db_connect.php

Code: Select all

<?php

//require the PEAR::DB classes.

require_once 'DB.php';


$db_engine = 'mysql';
$db_user = '---';
$db_pass = '---';
$db_host = 'localhost';
$db_name = '---';

$datasource = $db_engine.'://'.
                          $db_user.':'.
                          $db_pass.'@'.
                           $db_host.'/'.
                            $db_name;


$db_object = DB::connect($datasource, TRUE);

/* assign database object in $db_object,

if the connection fails $db_object will contain

the error message. */

// If $db_object contains an error:

// error and exit.

if(DB::isError($db_object)) &#123;
        die($db_object->getMessage());
&#125;

$db_object->setFetchMode(DB_FETCHMODE_ASSOC);

// we write this later on, ignore for now.

include('check_login.php');

?>
login.php

Code: Select all

<?php

// database connect script.

require 'db_connect.php';

if($logged_in == 1) &#123;
        die('You are already logged in, '.$_SESSION&#1111;'username'].'.');

&#125;


?>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php

if (isset($_POST&#1111;'submit'])) &#123; // if form has been submitted


        /* check they filled in what they were supposed to and authenticate */
        if(!$_POST&#1111;'uname'] | !$_POST&#1111;'passwd']) &#123;
                die('You did not fill in a required field.');
        &#125;

        // authenticate.

        if (!get_magic_quotes_gpc()) &#123;
                $_POST&#1111;'uname'] = addslashes($_POST&#1111;'uname']);
        &#125;

        $check = $db_object->query("SELECT username, password FROM users WHERE username = '".$_POST&#1111;'uname']."'");

        if (DB::isError($check) || $check->numRows() == 0) &#123;
                die('That username does not exist in our database.');
        &#125;

        $info = $check->fetchRow();

        // check passwords match

        $_POST&#1111;'passwd'] = stripslashes($_POST&#1111;'passwd']);
        $info&#1111;'password'] = stripslashes($info&#1111;'password']);
        $_POST&#1111;'passwd'] = md5($_POST&#1111;'passwd']);

        if ($_POST&#1111;'passwd'] != $info&#1111;'password']) &#123;
                die('Incorrect password, please try again.');
        &#125;

        // if we get here username and password are correct,
        //register session variables and set last login time.

        $date = date('m d, Y');

        $update_login = $db_object->query("UPDATE users SET last_login = '$date' WHERE username = '".$_POST&#1111;'uname']."'");

        $_POST&#1111;'uname'] = stripslashes($_POST&#1111;'uname']);
        $_SESSION&#1111;'username'] = $_POST&#1111;'uname'];
        $_SESSION&#1111;'password'] = $_POST&#1111;'passwd'];
        $db_object->disconnect();
?>

<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; border-width: 0" bordercolor="#111111" width="100%" id="AutoNumber1" height="100%">
      <tr>
        <td width="60%" style="border-style: none; border-width: medium" height="31">
<font face="verdana"><blockquote>
Login was successful.
<p>&nbsp;</td>
  </tr>
</table>

<?php

&#125; else &#123;        // if form hasn't been submitted

?>


<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; border-width: 0" bordercolor="#111111" width="100%" id="AutoNumber1" height="100%">
        <td width="60%" style="border-style: none; border-width: medium" height="31">
<form action="<?php echo $_SERVER&#1111;'PHP_SELF']?>" method="post">
<table border="0" cellspacing="1" bgcolor="ffffff" class=bordercolor align=left cellpadding="3" width="400">
<tr><td bgcolor="ffffff"><font face="Verdana" color="000000" size="1">Username:</td><td bgcolor="ffffff">
<input type="text" name="uname" maxlength="40">
</td></tr>
<tr><td bgcolor="ffffff"><font face="Verdana" color="000000" size="1">Password:</td><td bgcolor="ffffff">
<input type="password" name="passwd" maxlength="50">
</td></tr>
<tr><td colspan="2" align="center" bgcolor="ffffff">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<p>&nbsp;</td>
  </tr>
</table>

<?php
&#125;
?>
</body>
</html>
Anything else you think you'll need?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I've not done an in-depth look but open db_connect.php and put session_start(); at the top of it.

Include ?'.SID.' in your URL's too.

I could not see session_start(); anywhere in your code so essentially sessions will not be passed around. Putting it at the top of db_connect.php will put it at the top of ech page you have require 'db_connect.php'; on.

Looks like the actual assignment of the session variables is ok though ;-)

Good Luck!
User avatar
ol4pr0
Forum Regular
Posts: 926
Joined: Thu Jan 08, 2004 11:22 am
Location: ecuador

Post by ol4pr0 »

Code: Select all

$session = array("key"=>"value",
				 "key2"=>"value2",
				 "key3"=>"value3",
				 "key4"=>"value4",
				 "key5"=>"value5");
session_start();
$_SESSION = $session;
print_r($_SESSION);
Enjoy :)
Post Reply