getting table info by current user id

Discussion in 'PHP' started by ScottDB, May 27, 2011.

  1. #1
    Hi I can figure out how to bring up all or part of a table on a page but how do I get it to bring up just the table info for just the current user on a membership site. Im using phpmyadmin.
    I assume that the only thing I would have to change or add to would be this part of the code
    
    mysql_connect(localhost,$user,$password);
    @mysql_select_db($database) or die( "Unable to select database");
    $query="SELECT * FROM users";
    $result=mysql_query($query);
    
    Code (markup):

     
    ScottDB, May 27, 2011 IP
  2. mlblinco

    mlblinco Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Here is what i would recommend, you should create a separate connect file. Then just require it in each file.

    If you would like me to help, then i would need to know more about your problem.

    Thanks,

    Michael
     
    mlblinco, May 28, 2011 IP
  3. TSelbeck

    TSelbeck Peon

    Messages:
    26
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yeah. If the user is on a membership site.. it's a little more complicated than just getting the details of a particular user. You'll of course need to first verify the user is logged in, etc.

    As mlblinco suggested, ideally you need a separate file for your database connection

    
    
    // You need some way of having the users ID, which is going to have come from
    // another query, which validates the user. Below, it's from a class (I am not sure
    // on how you have done if, if you have done it at all
    
    $user_id = $user->id;
    
    $query="SELECT * FROM `users` WHERE `id` = '{$user_ID}' LIMIT 1";
    
    $result=mysql_query($query);
    
    
    PHP:
     
    TSelbeck, May 28, 2011 IP
  4. ScottDB

    ScottDB Greenhorn

    Messages:
    95
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #4
    Yes it is on a membership site and I have the database info stored in a config.php file. On the top of my php page I have the following code for the members only pages where I want to display the data.
    
    <?PHP
    require_once("./include/membersite_config.php");
    
    if(!$fgmembersite->CheckLogin())
    {
        $fgmembersite->RedirectToURL("login.php");
        exit;
    }
    
    ?>
    
    Code (markup):
    I know this code is a little different but it works and wont let you view the page unless you are loged in. Here is the code for the queery I am trying to run on the profile page. Notice that the data base information is in the query. I am wondering if I have the database info in the config file is there a way to call it up and not have to put that in every query I make?
    
    <?php
    $user="xxxxx";
    $password="xxxxxxxxx";
    $database="scott_test";
    mysql_connect(localhost,$user,$password);
    @mysql_select_db($database) or die( "Unable to select database");
    $query="SELECT * FROM users";
    $result=mysql_query($query);
    
    Print "<table border cellpadding=0>"; 
     while($info = mysql_fetch_array( $result )) 
     { 
     Print "<tr>"; 
     Print "<th>Member Id:</th> <td>".$info['id_user'] . "</td></tr> "; 
     Print "<tr>";
     Print "<th>Name:</th> <td>".$info['name'] . "</td></tr> "; 
     Print "<tr>";
     Print "<th>Email:</th> <td>".$info['email'] . "</td></tr> "; 
     Print "<tr>";
     Print "<th>Member Since:</th> <td>".$info['member_since'] . "</td></tr> ";
     Print "<tr>";
     Print "<th>Username:</th> <td>".$info['username'] . " </td></tr>"; 
     } 
     Print "</table>"; 
     ?> 
    Code (markup):
    Should I put the code given into this code to get the info by the members ID?
     
    ScottDB, May 28, 2011 IP
  5. TSelbeck

    TSelbeck Peon

    Messages:
    26
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    ./include/membersite_config.php must have some sort of database connection code to it. Maybe that has an include file to connect to the database?

    If not, you should create a file such as.. connect.php

    
    <?
    $user="xxxxx";
    $password="xxxxxxxxx";
    $database="scott_test";
    mysql_connect(localhost,$user,$password);
    ?>
    
    PHP:
    Then you can use..

    
    include('connect.php');
    
    PHP:
    On all of the pages that require a connection. From the above code where you have

    $fgmembersite->CheckLogin()
    Code (markup):
    Perhaps take a look in there, to see if you can call

    $fgmembersite->id
    Code (markup):
    EDIT: The above code that you have will query the database for ALL users in the users table. The initial code that I wrote will allow you to get the specific user's id.. but you need to know where the users id is stored (as in, what variable)
     
    TSelbeck, May 28, 2011 IP
  6. DomainerHelper

    DomainerHelper Well-Known Member

    Messages:
    445
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    100
    #6
    Here is the clean and un-ghetto way to do it. Do not use mysql_fetch_array, use mysql_fetch_assoc() instead. mysql_fetch_array build an associative array AND a numeric array, wasting time and resources. This is much cleaner, scalable, scure and faster code than the other examples given:

    _database.php:

    
    $dbname = 'DATABASE_NAME_HERE';
    $dbuser = 'DATABASE_USER_HERE';
    $dbpass = 'PASSWORD_HERE';
    $dbhost = 'localhost';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or exit(mysql_error());
    mysql_select_db($dbname, $conn) or exit(mysql_error());
    
    PHP:


    Example one, all users:

    <?php
    //get all users
    require_once('_database.php');
    $sql = mysql_query('SELECT * FROM `users`') or die(mysql_error());
    if (mysql_num_rows($sql) == 0) {
    	die('No users in db');
    } else {
    	while($r = mysql_fetch_assoc($sql)) {
    		$user_id = $r['id_user'];
    		$name = stripslashes($r['name']);
    		$email = stripslashes($r['email']);
    		$username = stripslashes($r['username']);
    		$membersince = stripslashes($r['membersince']); // remove stripslashes if timestamp
    		echo '
    			<div style="clear:both;margin-top:6px;">
    				<ul>
    					<li>' . $user_id . '</li>
    					<li>' . $name . '</li>
    					<li>' . $email . '</li>
    					<li>' . $username . '</li>
    					<li>' . $membersince . '</li>
    				</ul>
    			</div>
    		';
    	}
    }
    ?>
    PHP:

    Example two, single user:

    <?php
    //get  a single user
    require_once('_database.php');
    if (!empty($_REQUEST['uid'])) {
    	$uid = (int)$_REQUEST['uid'];
    } else {
    	die('No such user in db.');
    }
    $sql = mysql_query('SELECT * FROM `users` WHERE `id_user`="' . $uid . '"') or die(mysql_error());
    if (mysql_num_rows($sql) == 0) {
    	die('No such user in db.');
    } else {
    	$r = mysql_fetch_assoc($sql);
          	$user_id = $r['id_user'];
          	$name = stripslashes($r['name']);
          	$email = stripslashes($r['email']);
          	$username = stripslashes($r['username']);
          	$membersince = stripslashes($r['membersince']); // remove stripslashes if timestamp
          	echo '
          		<div style="clear:both;margin-top:6px;">
          			<ul>
          				<li>' . $user_id . '</li>
          				<li>' . $name . '</li>
          				<li>' . $email . '</li>
          				<li>' . $username . '</li>
          				<li>' . $membersince . '</li>
          			</ul>
          		</div>
          	';
    	exit();
    }
    ?>
    PHP:

    You can also do this, this would allow yu to add fields on the fly and the data show in your admin panel without code changes.....

    <?php
    // get  a single user and echo all data for that user
    require_once('_database.php');
    if (!empty($_REQUEST['uid'])) {
    	$uid = (int)$_REQUEST['uid'];
    } else {
    	die('No such user in db.');
    }
    $sql = mysql_query('SELECT * FROM `users` WHERE `id_user`="' . $uid . '"') or die(mysql_error());
    if (mysql_num_rows($sql) == 0) {
    	die('No such user in db');
    } else {
    	$main = '<div style="clear:both;margin-top:6px;"><ul>';
    	foreach(mysql_fetch_assoc($sql) as $key=>$value) {
    		$$key = stripslashes($r[$key]);
    		$main .= '
    			<li>' . $key . ': ' . $value . '</li>
    		';
    		$main .= '</div>'
    	}
    }
    ?>
    PHP:
     
    Last edited: May 28, 2011
    DomainerHelper, May 28, 2011 IP
  7. ScottDB

    ScottDB Greenhorn

    Messages:
    95
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #7
    Thanks for the replies. I will have to try your last suggestion DomainerHelper, a little later. Got to go pick up the kid right now.

    I am a real newbie to php and sql. I just started learning this stuff and building a web site from scratch so I can understand how it all works. Havent built an admin section yet. That is my next project. Can you elaberate on what you meant by "this would allow yu to add fields on the fly and the data show in your admin panel without code changes....."

    Also in your second suggestion I noticed you stated something about timestamp for the member_since field. I have not been able to get this to work. I have posted for help with this on this thread. http://forums.digitalpoint.com/showthread.php?t=2189497#post16288931
     
    Last edited: May 28, 2011
    ScottDB, May 28, 2011 IP
  8. DomainerHelper

    DomainerHelper Well-Known Member

    Messages:
    445
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    100
    #8
    If you wanted to add the member's date of birth, for example, you add the collumn "DOB" to the database as an int(15). Then store the value of the php function time() to that. Then in your admin panel, when using the 4th code snipet to show user info, it will automatically show the DOB along with the values of the other user fields (id_user,username,name,email,DOB,membersince).

    To use a timestamp for membersince, do the same. Edit the database collumn you have named "membersince" and change it to int(15). Then when the member signs up, insert the value of time() into that field. A timestamp is the number of seconds passed since January 1st, 1970. So when you go to pull out the timestamp and convert it to a human readable date you do this:

    <?php
    $membersince_humanread = date('F j, Y, g:i a T',$membersince);
    echo ;
    // will show the date: May 28, 2011, 2:50 pm EST
    ?>

    More info on php date(): http://php.net/manual/en/function.date.php

    More info on php time(): http://php.net/manual/en/function.time.php

    Here is that snippet but also converting the membersince timestamp to human readable:

    <?php
    // get  a single user and echo all data for that user
    require_once('_database.php');
    if (!empty($_REQUEST['uid'])) {
    	$uid = (int)$_REQUEST['uid'];
    } else {
    	die('No such user in db.');
    }
    $sql = mysql_query('SELECT * FROM `users` WHERE `id_user`="' . $uid . '"') or die(mysql_error());
    if (mysql_num_rows($sql) == 0) {
    	die('No such user in db');
    } else {
    	$main = '<div style="clear:both;margin-top:6px;"><ul>';
    	foreach(mysql_fetch_assoc($sql) as $key=>$value) {
    		$$key = stripslashes($r[$key]);
    		if ($key == 'membersince') {
    			$main .= '
    				<li>' . $key . ': ' . date('F j, Y, g:i a T',$value) . '</li>
    			';
    		} else {
    			$main .= '
    				<li>' . $key . ': ' . $value . '</li>
    			';
    		}
    		$main .= '</div>'
    	}
    }
    ?>
    PHP:
     
    DomainerHelper, May 28, 2011 IP
  9. ScottDB

    ScottDB Greenhorn

    Messages:
    95
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #9
    I understand all of what you said except for "Then when the member signs up, insert the value of time() into that field".

    I have set the member_since to INT (15) not null. It shows in the data base but upon register it just shows 0. I assume that when you say to set the value of time int that field you are talking about the function collum in the database. In it's list is a number of different time funtions. There is Unix_timestamp, timestamp, UTC_timestamp. Is this one of the funtions that you are talking about for value of time?
     
    ScottDB, May 28, 2011 IP
  10. DomainerHelper

    DomainerHelper Well-Known Member

    Messages:
    445
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    100
    #10
    No, here is what I mean. At the time that php inserts the user into the database:

    
    mysql_query('INSERT INTO `TABLENAME` SET `membersince`="' . time() . '", `username`="' . $username . '", `email`="' . $email . '", `name`="' . $name . '"') or die(mysql_error());
    
    PHP:
    That will do it.
     
    DomainerHelper, May 29, 2011 IP
  11. ScottDB

    ScottDB Greenhorn

    Messages:
    95
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #11
    Tried running that queery in phpmyadmin and got the following error message.
    [CODE#1064 - 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 'mysql_query('INSERT INTO `users` SET `member_since`=&quot;' . time() . '&quot;, `username`' at line 1
    mysql_query(
    'INSERT INTO `users` SET `member_since`="'.time(
    ). '", `username`="'.$username. '", `email`="'.$email. '", `name`="'.$name. '"'
    ) OR die(
    mysql_error(
    )
    )[/CODE]
     
    ScottDB, May 31, 2011 IP
  12. ScottDB

    ScottDB Greenhorn

    Messages:
    95
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #12
    Ok din't think about it untill after I posted. When I went back and noticed you said at the time php inserts data into database. So I edited my file that adds the info to the data base for users upon first time someone tries to join. This is a real simple script.

    Tried to keep with the way the code is written in the rest of the file. Here is what I put but getting an error - Parse error: syntax error, unexpected T_VARIABLE, expecting ';' or '{' in xxxx/xxxx

    I put quote tags around area I edited - was working before I made this edit.


       function CreateTable()
        
        {
            $qry = "Create Table $this->tablename (".
                    "id_user INT NOT NULL AUTO_INCREMENT ,".
                    "name VARCHAR( 128 ) NOT NULL ,".
                    "email VARCHAR( 64 ) NOT NULL ,".
                    "member_since INT( 16 ) NOT NULL ,".             
                    "username VARCHAR( 16 ) NOT NULL ,".
                    "password VARCHAR( 32 ) NOT NULL ,".
                    "confirmcode VARCHAR(32) ,".
                    "PRIMARY KEY ( id_user )".
                    ")";
                    
            if(!mysql_query($qry,$this->connection))
            {
                $this->HandleDBError("Error creating the table \nquery was\n $qry");
                return false;
            }
            return true;
        }
     [QUOTE]   function InsertIntoTable ()
         
           $qry = 'INSERT INTO `users` (SET `member_since`="' . time() . '", `username`="' . $username . '", `email`="' . $email . '", `name`="' . $name . '"') or die(mysql_error());
        }[/QUOTE]    
        function InsertIntoDB(&$formvars)
    
    Code (markup):
     
    ScottDB, Jun 1, 2011 IP