Individual Username from a Database - php

I have a database running and I'm currently printing out in a website, in a "php block" the usernames of the database. I achieved it with this
if ($db_handle) {
print "Database ISSSSS Found ";
$SQL = "SELECT * FROM `database.com`.`users`";
$result = mysql_query($SQL);
//print $result;
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['username'] . "<BR>";
}
mysql_close($db_handle);
}
However this gives me a giant string of all the users (I currently have 4). How do I make it so its just the individual user accessing their profile through the website

Typically, when someone logs in, you would store non sensitive information about the user in the session. This way, you can get to it quickly without needing to make database calls on every page. For instance, if you wanted to show their username in the pages header, you would always have their username handy to do so. Then, when they go to view their profile, you can use that username you stored as part of your SQL WHERE clause to pull in information pertaining only to that specific user.

Use WHERE username = 'yourusername' in your SQL query.
That shall fix your problem

Related

Get user information from mysql database

I'm trying to do a very easy user management.
I want to select and display the information from the mysql database.
I have connected to the database and it works fine. And I have a log in form and registration which works fine. Now when the user is logged in I want to display the information and the user should be able to update it.
Can i just use a simple thing like this:
<?php
$firstname= $_SESSION['user_name'];
$email= $_SESSION['user_email'];
if ($email!= null) {
echo $email;
}
else {
echo 'no email found';
}
?>
You are leaving a lot out, so it is hard to know what all you want to do, but you can use the UPDATE statement to change the database values which have already been inserted.
UPDATE users SET user_email = 'some_email'
WHERE user_name = 'some_user';
Other than that I'm not sure what you're asking for. The whole HTML form?

Printing an HTML page with unique number

I am having a php page in which i have captured different values from the previous page, There is also a print button, Which prints all these fields including the unique number. When user clicks on the print button record will be inserted in database and print window displays on the screen. But the problem is there is a unique number on html page, For example if two persons are login at the same time, The will get same unique number, and both will be able to print the same page having same unique number.
How i can control this issue, I also tried to redirect the user to the previous page but its not working.
Here is my php page, Which i am calling using ajax
<?php
$conn = mysql_connect('localhost','','') or die ("");
mysql_select_db("") or die ("Database Problem");
$query = "select * from print where a = $a;
$result = mysql_query($query);
if(mysql_num_rows($result) == 0)
{
$query = "INSERT INTO print () VALUES ()
$result = mysql_query($query) or die();
if(mysql_affected_rows()<>1)
{
header ("Location:mainpage.php?uniquenumber=xy");
}
}
you can use unisid http://php.net/manual/en/function.uniqid.php
To generate an unique id
What is this uniquenumber needed for in the client side? I mean having it accessible and editable for the users is kinda dangerous if it's an important value.
If you just need this number to tell apart the different entries in the print table, why not just use and auto_increment index for this table?
Another solution would be session variables. When a user succesfully logs in generate this unique ID based on multiple variables (username, time, browser), that will ensure there won't be repeated values for this ID. Then store the variable like this:
session_start();
$_SESSION['ID']=$unique_ID;
You can then read it in any other PHP script like this:
session_start();
$unique_ID=$_SESSION['ID'];
You can validate the unique number before inserting to database ( Before Printing also ). If the unique no is exist, throw a error message "unique no is already used " and give another unique number ( By loading the HTML Page again or doing something else ).

php/postgres - query output does not print on the browser

I am writing a simple user/login system in Php with postgresql.
I have a function that confirms whether username/passwords exists, which gets activated when a user presses the Login button.
public function confirmUserPass($username, $password){
$username=pg_escape_string($username);
/* Verify that user is in database */
$q = "SELECT password FROM users WHERE email = '$username'";
$result = pg_query($this->link,$q);
/* Do more operations */
}
I want to print the query stored in $results such that I can see it on the browser. When I do it in phppgAdmin using SQL it shows me the output but I cannot see it on the browser. I tried echo and printf but I could not see anything on the browser. I also tried to see view source from the browser but it shows nothing.
Can somebody help me with that?
Regards
From your code: $result = pg_query($this->link,$q);
As you've found already, trying to display the contents of $result from the line above will not give you anything useful. This is because it doesn't contain the data returned by the query; it simply contains a "resource handle".
In order to get the actual data, you have to call a second function after pg_query(). The function you need is pg_fetch_array().
pg_fetch_array() takes the resource handle that you're given in $result, and asks it for its the next set of data.
A SQL query can return multiple results, and so it is typical to put pg_fetch_array() into a loop and keep calling it until it returns false instead of a data array. However, in a case like yours where you are certain that it will return only one result, it is okay to simply call it once immediately after pg_query() without using a loop.
Your code could look like this:
$result = pg_query($this->link,$q);
$data = pg_fetch_array($result, NULL, PGSQL_ASSOC);
Once you have $data, then you've got the actual data from the DB.
In order to view the individual fields in $data, you need to look at its array elements. It should have an array element named for each field in the query. In your case, your query only contains one field, so it would be called $data['password']. If you have more fields in the query, you can access them in a similar way.
So your next line of code might be something like this:
echo "Password from DB was: ".$data['password'];
If you want to see the raw data, you can display it to the browser using the print_r() or var_dump() functions. These functions are really useful for testing and debugging. (hint: Wrap these calls in <pre> tags in order for them to show up nicely in the browser)
Hope that helps.
[EDIT: an after-thought]
By the way, slightly off-topic, but I would like to point out that your code indicates that your system may not be completely secure (even though you are correctly escaping the query arguments).
A truly secure system would never fetch the password from the database. Once a password has been stored, it should only be used in the WHERE clause when logging in, not fetched in the query.
A typical query would look like this:
SELECT count(*) n FROM users WHERE email = '$username' AND password = '$hashedpass'
In this case, the password would be stored in the DB as a hashed value rather than plain text, and the WHERE clause would compare that against a hashed version of the password that has been entered by the user.
The idea is that this allows us to avoid having passwords accessible as plain text anywhere in the system, which reduces the risk of hacking, even if someone does manage to get access to the database.
It's not foolproof of course, and it's certainly not the whole story when it comes to this kind of security, but it would definitely be better than the way you seem to have it now.
You must connect to database , execute query, and then fetch results.
try this example from php.net
<?php
public function confirmUserPass($username, $password){
$username=pg_escape_string($username);
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = "SELECT password FROM users WHERE email = '$username'";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
}
?>
http://php.net/manual/en/book.pgsql.php

Handling Sessions

Need some help with how to handle sessions. I am using ajax techniques to implement a group discussion platform and alot of its success depends on whether or not i can handle sessions properly, be able to see who is online etc. How can i do this efficiently. Remember, this is a typical single url ajax application where the server only responds to request. All of the form validation is done on the client side as the user enters his data. I need help with this. Below what have written so far.
<?php
include_once "../database/dbconnect.php";
session_start();
$username = isset($_POST["userNameLogin"]) ? $_POST["userNameLogin"] : $_SESSION["userNameLogin"];
$pwd = isset($_POST["passwordLogin"]) ? $_POST["passwordLogin"] : $_SESSION["passwordLogin"];
// Sending these messages to my client side validation code json-style.
if(!isset($username)){
echo("{message : 'NoName'}");
}
elseif(!isset($pwd)){
echo("{message : 'NoPW'}");
}
// creating the session variables to hold username and pwd
$_SESSION['userNameLogin'] = $username;
$_SESSION['passwordLogin'] = $pwd;
// calling the function incuded above to make connection to mysql db
dbConnection();
//query retrieves username and pwd from db and counts the result. if it is one, then they //certianly exist and if not unset the variables created above. The varibles were created
//above so i do not have to check if they exist before unsetting them.
$sQuery = "SELECT * FROM users WHERE
username = '$username' AND password = '$pwd'";
$result = mysql_query($sQuery) or die(mysql_error());
$intFound = mysql_num_rows($result);
if ($intFound == 0) {
unset($_SESSION['userNameLogin']);
unset($_SESSION['passwordLogin']);
// AD - Access Denied
echo("{message : 'AD'}");
}
else{
//a flag to set in the database who is currently online. value of 1 for users who are //online and zero for users who are not. If i want a list of those online, i check the //column called online and then check to see if the $_SESSION['username'] exist. If it //does then i know the user is online. That is what the second script is for. New to this //stuff, and do not know a better way of doing it
mysql_query("UPDATE users SET online = '1' WHERE username = '$username'") or die(mysql_error);
}
The above script should let the user login or deny access by sending messages to the validation code on client side.
As you can see, i am new to this stuff i having my share of problems. What can i do to make sure that sessions are set and unset properly i.e when user logs out.
secondly how can i monitor who is online and who is not using sessions. This is how i am trying to check who is currently online and then building a json file with the user names and sending it to the client. Json is easier to parse.
The script below tries to determine who is online
<?php
// this script determines which sessions are currently active by
// 1.) checking to see which online fields in the users table are set to 1
// 2.) by determining if a session variable has been set for these users.
// If it is not set, it means user is no longer active and script sets its online field in the users table to zero.
// After doing this, the script, then queries the users table for online fields with values one, writes them to an
// array and passes them to the client.
include_once "../database/dbconnect.php";
//include "../validation/accessControl.php";
$tempActiveUsers = array();
$activeUsers = array();
$nonActiveUsers = array();
dbConnection();
$sql = "SELECT username from users WHERE online = '1' ";
$active_result = mysql_query($sql) or die(mysql_error);
if($active_result){
while($aValues = mysql_fetch_array($active_result)){
array_push($tempActiveUsers, $aValues['username']);
}
}
forEach($tempActiveUsers as $value){
/*if($_SESSION['$value'] == $value){
$activeUsers += $value;
} */
if(isset($_SESSION['userNameLogin']) == $value){
array_push($activeUsers, $value);
}else{
array_push($nonActiveUsers, $value);
}
}
forEach($nonActiveUsers as $value1){
$sql1 = "UPDATE users SET online='0' WHERE username = '$value1'";
$set_result = mysql_query($sql1) or die(mysql_error);
}
$length = sizeof($activeUsers);
$len = 1;
$json ='{"users" : {';
$json .= '"user":[';
forEach($activeUsers as $value2){
$json .= '{';
$json .= '"username" : "' .$value2.'" }';
if($len != $length){
$json .= ',';
}
$len++;
}
$json .= ']';
$json .= '}}';
echo $json;
Please look through and give some advice. Will appreciate that very much. My project framework is up and good, but i can implement much user functionality yet because i cann't track who is online and how to manage thier sessions. If you need more background info let me know. Thanks in advance
Add 'Log out' button and click event handler on it which makes an ajax request to server to stop session by unsetting session vars or destroying session completely, and on ajax completion callback put a function to update user interface to show user is logged out.
Log in procedure can be done as follows: user clicks 'Log in' button and some form asking for user name and password appears. Then submit this form with ajax to a server script like your first one. Server script checks whether user name and password are valid and returns authentication information to a client via callback: failure notice upon failed login or some information about user currently logged in, e.g. user name, fullname and anything you might need about this user on client side in js. Then your client script proceeds according to login status returned from server-side script.
You should always remember about security.
Before sending any sensitive data to a client side with json, you shoud always check if session is valid and started. Client-side scripts could be easily modified and executed without your control and you should prevent undesired activity only on server side.
You should apply some escaping on user-POSTed fields before using them in sql queries to avoid sql injection attacks, e.g. by using mysql_escape_string().
And instead of building json strings, you can use json_encode() which works good for primitives, objects and arrays, you'll save some time.

PHP Links to User Profiles After Membership

I already have written a login and register script. The user can login to their account edit their details etc. The details are stored in a users table which has many different data properties related to the user.
I was wondering, how do I make it so they can view their profile and it shows all the data they input. For example, if somebody with username "bob" registered and changed his data, he can click a link "view profile" and he can see his public user profile. I know how to fetch entries and display the data but my problem is I don't understand how to make a profile for my users that can be seen by others and/or themselves. I want these pages to be dynamically created for each user.
Also, if I had a page that retrieved all the recently registered members, it could link to their profile pages.
It is a very common thing across websites and I know there are CMS's that already do this like drupal but I want to code a small controlled solution by myself. Thanks!
Make your page 'profile.php'
1) Pass id to that page using Get String. Link would be : ....../profile.php?id=3
To learn more about Get and Post Method of form submission. And how PHP handles it ($_POST & $_GET) google it.
2) In that page 'profile.php'
$id=isset($_GET['id'])?$_GET['id']:-1;
settype($id , "int");
if($id<1)
{
//wrong id, may be redirect
header('Location : another-page.php');
die();
}
// use this $id to get information from db and display the information
3) If you want to dynamically tell the person that what his profile link is:
Supposing you have $id of that person :
$link = '...../profile.php?id=' . $id;
Please consider learning basic php first. Like cookies, get, post, functions, db handling, sessions, string handling, array handling, global variables.
Well, just create a page say userprofile.php that gets a parameter called id (I assume your users have id's .. otherwise have username). If the page is called with no parameter, the page will use the current session user as the profile id and will make all fields editable, otherwise, if it's passed with say "userprofile.php?id=123", then it will display a non-editable version for other members. You can also do a check to see if the session user is the same as the one whose profile is requested, in which case, you want to make the page editable as well.
Are you looking for something like this (an amalgamation of what has been posted and some extra stuff):
$SQL = "SELECT ID, First_Name, Last_Name, User_Name FROM Users" .
"WHERE ID = " . $_GET['id'];
$con = mysql_connect('server', 'user', 'password');
$db = mysql_select_db('database_name', $con);
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print "User ID: " . $db_field['ID'] . "<BR>";
print "User Name: " . $db_field['User_Name'] . "<BR>";
print "First Name: " . $db_field['First_Name'] . "<BR>";
print "Last Name: " . $db_field['Last_Name'] . "<BR>";
}
When you want to create a link to their user page, something like this:
print "" . $db_field['User_name'] . "";
This takes the ID you pass through from a link on a page, such as http://servername/page/list.php?ID=123 and then the above code retreives whatever information you want (via the SELECT statement) in the database. Then you just lay the information out however you want.

Categories