SitePoint Sponsor

User Tag List

Results 1 to 15 of 15
  1. #1
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Using session variable in SQL statement

    Hi

    I am reasonably new to PHP and I have a problem passing a session variable in my SQL statement.

    Current attempt as follows:

    $result = @mysql_query("SELECT * FROM
    details WHERE uname= 'echo $check["uname"]'");

    I have spent some time trying to get this to work without success.

    <?php echo $check["uname"] ?> will show the variable on the page so it is being set, I just cannot figure how to put this into my SQL statement despite looking at previous forum threads and the PHP manual.

    A push in the right direction, with explanation, would be appreciated.

    Regards
    Colin

  2. #2
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    Colin,
    You need to enclose the variable in single quotes
    PHP Code:
    $result = @mysql_query("SELECT * FROM 
    details WHERE uname= '"
    $check['uname']."'"); 
    And you dont need to echo the variable either.

    note the single opening quote ' followed by the double quote " and the period .
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  3. #3
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy

    Thanks for the quick reply.

    It would seem that I have further problems as this still does not give me the results from the DB relating to the session variable.

    <?php
    // query database and return results

    $result = @mysql_query("SELECT * FROM
    details WHERE uname= '". $check['uname']."'");

    if (!$result) {
    echo("<p>Error performing query: " . mysql_error() .
    "</p>");
    exit();
    }
    // Display the text in a paragraph
    while ( $row = mysql_fetch_array($result) ) {
    echo("<p>" . $row["company"] .
    "</p>");
    }

    ?>

    Regards
    Colin

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2004
    Posts
    1,647
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    can u show us where u get $check["uname"]....
    PHP Code:
    $x $check["uname"];
    $result mysql_query("SELECT * 
                           FROM details 
                           WHERE uname = '
    $x'"); 
    cheers

  5. #5
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    I am assuming that your $check['uname'] is based on your session variable?
    If so why not use your session variable directly?
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  6. #6
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    I am using a login/admin script called vAuthenticate. This uses 3 include files to manage the session status. I, maybe incorrectly, assumed that because I could output the session variable on the page then I could simply enter this into my SQL statement and away we go.

    If I hard code the name of the session variable into my statement then I still do not get output?

    Regards

    Colin

  7. #7
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    Normally you can put the variables into the query...
    PHP Code:
    <?php
    // query database and return results

    $query"SELECT * FROM details 
    WHERE uname= '"
    $check['uname']."'";
    $result mysql_query($query) or die mysql_error();
    # for testing purposes, echo the query and see if it was you expect.
    echo $query;

    // Display the text in a paragraph
    while ( $row mysql_fetch_array($result) ) {
    echo(
    "<p>" $row["company"] .
    "</p>");
    }

    ?>
    Echo the query and see if it gives you what you expect....
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  8. #8
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy

    Hi

    Ok that just produces a blank page so there must be a problem with the query itself?

    Colin

  9. #9
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    bare bones
    PHP Code:
    $querymysql_query("SELECT * FROM details
    WHERE uname= '"
    $check['uname']."'") or die (mysql_error());
    echo 
    $query
    Try that!
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  10. #10
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    OK

    As suspected this is something to do with the vAuthenticate script. The SQL output is Resource id #8 not a "uname".

    Back to the drawing board on this one rewriting a whole new and less complicated login system.

    Thanks for your help it has at least been a learning exercise for me, sorry to have wasted your time on this.

    Regards

    Colin

  11. #11
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    Search the php forum for login scripts cos there are quite a few here.....
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  12. #12
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot for your help.

    Colin

  13. #13
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Exclamation

    Hi again

    I have strung together a login script using threads from these forums and it is working OK.

    I still have the problem with passing the session variable in the SQL statement though.

    Code:

    <?php echo $_SESSION['username'] ?> // <--- This outputs the session username correctly

    <?php
    // connect to database

    $dbcnx = @mysql_connect('localhost', '', '');
    if (!$dbcnx) {
    echo( '<p>Unable to connect to the ' .
    'database server at this time.</p>' );
    exit();
    }

    if (! @mysql_select_db('deewebs') ) {
    die( '<p>Unable to locate the deewebs ' .
    'database at this time.</p>' );
    }
    ?>


    <?php

    $query= mysql_query("SELECT * FROM users
    WHERE username= '". $_SESSION['username']."'") or die (mysql_error());
    echo $query;
    ?>

    The result from the echo $query is " Resource id #3 " No idea where this comes from at all, I have only one row in my DB at the moment with an ID of "1"

    Any help on this is most certainly welcomed.

    Regards

    Colin


  14. #14
    SitePoint Wizard swdev's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As you say, the 'Resource id #2' is being displayed by the echo $query line. You need to actually retrieve the results from the query like so

    PHP Code:
      $row mysql_fetch_assoc($query);
      if (
    false == $row)
      {
      
    // some error getting the data
      
    die ('Failed to get data ' mysql_error());
      }
      else
      {
        echo 
    $row['COLUMN_NAME'];
      } 
    COLUMN_NAME should be replaced with the name of one of your columns in the table.
    $row is an associatvie array that contains all the data for 1 row retrieved from your query.

    Hope this helps

  15. #15
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    468
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So to conclude I now have this as a login script:

    Login.php

    <?php

    // Initialize Session
    session_start();
    header ("Cache-control: private") ; //IE 6 Fix


    // Check for previous authentication
    if ( isset($_SESSION['auth']) )
    {

    $loc = 'index.php' ;
    header("location:$loc");
    exit;
    }

    // Error Messages
    $msg = array();
    $msg['login'] = 'Login to access client section';
    $msg['invalid'] = 'Username/password incorrect';
    $msg['logout'] = 'Log out successful';

    // Check for error
    if ( isset($_GET['reason']) && !empty($_GET['reason']) )
    {
    $error = $_GET['reason'];
    echo '<font color="#FF0000"><b>' . $msg[$error] . '</b></font><br />';
    }

    ?>

    <FORM method="post" action="process_login.php" onSubmit="return validateForm(this)">
    <p align="center">
    <p>Please enter your Username and Password below and Login.</p>
    <p>Username:
    <input type="text" name="username" value="" class="inputbox">
    <br>
    <br>
    Password:
    <input type="password" name="password" value="" class="inputbox">
    <p class="copy">
    <input type="submit" name="do_login" value="Login" class= "button">
    </p>
    </form>



    Process_login.php:

    <?php

    // Initialize Session
    session_start();
    header ("Cache-control: private") ; //IE 6 Fix

    // Check for previous authentication
    if ( isset($_SESSION['auth']) )
    {

    $loc = 'index.php' ;
    header("location:$loc");
    exit;
    }

    // Database Connection
    $dbh = @mysql_connect('localhost','','');
    if ( !$dbh )
    {
    die ('Database Error - Connect');
    }
    @mysql_select_db('your_database',$dbh);

    // Get Form Contents
    if ( isset($_POST['do_login']) )
    {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 0,1";

    $result = @mysql_query($sql);
    if ( !$result )
    {
    die('Database Error - Query');
    }
    if ( mysql_num_rows($result) == 1 )
    {
    $_SESSION['auth'] = 1;
    $_SESSION['username'] = $username;

    $loc = 'index.php';
    header("location:$loc");
    exit;
    }
    else
    {
    $loc = 'login.php?reason=invalid';
    header("location:$loc");
    exit;
    }

    }
    else
    {
    $error_loc = 'login.php?reason=login';
    header("location:$error_loc");
    exit;
    }

    ?>



    Index.php:

    <?php //<-- Place this at line 1 of page you want to protect

    // Initialize Session
    session_start();
    header ("Cache-control: private") ; //IE 6 Fix

    // Check for previous authentication
    if ( !isset($_SESSION['auth']) )
    {
    $loc = 'login.php?reason=login';
    header("location:$loc");
    exit;
    }

    ?>





    Logout.php:

    <?php

    // Initialize Session
    session_start();

    // Destroy Session
    $_SESSION = array();
    session_destroy();

    // Redirect to login.php
    $loc = 'login.php?reason=logout';
    header("location:$loc");
    exit;

    ?>


    Datapage.php

    <?php //<-- Place this at line 1 of page you want to protect

    // Initialize Session
    session_start();
    header ("Cache-control: private") ; //IE 6 Fix

    // Check for previous authentication
    if ( !isset($_SESSION['auth']) )
    {
    $loc = 'login.php?reason=login';
    header("location:$loc");
    exit;
    }

    ?>


    <?php
    // connect to database

    $dbcnx = @mysql_connect('localhost', '', '');
    if (!$dbcnx) {
    echo( '<p>Unable to connect to the ' .
    'database server at this time.</p>' );
    exit();
    }

    if (! @mysql_select_db('your_database') ) {
    die( '<p>Unable to locate the ' .
    'database at this time.</p>' );
    }
    ?>


    <?php
    $result = mysql_query("SELECT * FROM tablename
    WHERE username= '". $_SESSION['username']."'") or die (mysql_error());

    while ($row = mysql_fetch_assoc($result)) {
    print $row['fieldname'];
    }
    ?>


    As a PHP newbie I hope I have got this right (I am sure you will put me right if I haven't!!!!!!) and it will be of use to others looking for a simple login script.

    If it can be improved upon then additions more than welcome but try to keep it simple for us newbies.

    Regards

    Colin


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •