Display particular loggedin user name - php

I want to display the particular username after login successful. by using session I am calling my username. But it is displaying all user names.
Please give suggestion to display only particular username.
Here is my code.
In session :
$_SESSION ['admin_name'] = $row['name'];
$admin_name = $_SESSION['admin_name'];
Inserting in to DB :
$sql = "INSERT INTO account_info (name)
VALUES ( '$admin_name')";
Displaying :
<?php
$count = 1;
$sel_query = "Select * from account_info ORDER BY id;";
$result = mysql_query($sel_query);
while ($row = mysql_fetch_assoc($result)) {
?>
<td align="left"><?php echo $row["name"]; ?></td>
<?php
$count++;
}
?>
I think while displaying I need to filter name. Please reply to me anybody knows how to filter.
Update:

You should re-approach this as it's poor design, but to get what you want to achieve:
while($row = mysql_fetch_assoc($result)) {
if($row['name'] == $_SESSION['admin_name']) {
...
}
}
Or even better...
$sel_query="Select name from account_info WHERE name = '$admin_name'";

$sel_query="Select * from account_info WHERE name = '$admin_name' ";

You don't need to save session values into database to show it after login successful.
Only store it into session array like this:
$_SESSION['user_name'] = $row['name'];
and in login page check this session array is set or not.If set then display it
like:
if(isset($_SESSION['user_name'])) { echo $_SESSION['user_name']; }

You are getting the all username because of this query:
Select * from account_info ORDER BY id;
This will return all user data, you need to add username in WHERE clause for particular user as:
Select * from account_info WHERE name = '$admin_name';
More important, i didn't see session_start() function in your code, don't forgot to use this, otherwise you can't get the $_SESSION values.
Other important thing, your code is open for SQL Injection, you can use Prepared Statement for preventing SQL Attack. This will help you: How can I prevent SQL injection in PHP?
Very Special point, mysql_* is deprecated and closed in PHP 7.
Side Notes:
In your current query, no need to use ORDER BY id because when you use WHERE for particular user this part should be useless here.
Don't know, where are you using $count++; in your requirement, you need to print only particular user data so this is also useless here.

Related

How do I get the user ID of a user from their username via sessions in php?

I have to get the user ID from the database, but the only session information I can get from the login page is the username and the password. I am able to get the username, but when I try to run a query to get the id using that info, it returns nothing. Here is the code:
$_SESSION['username'] = $username;
$connect = mysqli_connect("xxxx","xxxx","xxxx", "xxxx");
$IDquery = "SELECT UserID FROM User WHERE Username = ".$username.";";
$result = $connect->query("SELECT UserID FROM User WHERE Username = '$username';");
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$user_id = $row["UserID"];
$_SESSION["UserID"] = $user_id;
}
How can I get the user ID if I only have the username?
I do suspect that this:
$_SESSION['username'] = $username;
Should actually be:
$username = $_SESSION['username'];
That is: you want to retrieve the username from the session rather than setting the session variable.
Side note: you should really use parameterized queries rather than mungling variables into the query string. This is more efficient, and safer, as it prevents you from SQL injection. You can have a look at this famous SO post for the whys and hows.
It looks like the issue is how you are trying to use the $username variable into the query (you should also, as mentioned before, use parameterized queries).
First of all, make sure that before sending the $username you know what's is inside it.
try for example:
var_dump($_SESSION['username']);
Put it before you execute the query.
Sometimes it helps to remove variables from the middle if not sure how it is being assigned:
$IDquery = "SELECT UserID FROM User WHERE Username = ".$_SESSION['username'].";";
Also, you want to be sure that the session is filled with the information you are going to use at the same time the user is authenticated. that should remove queries in the middle of the session.

Carry over specific data from mysql query result when user selects data

This is my first ever question on stackover flow so hope i explain it well. I am fairly new to php/js/html and i have run into a problem. I query my database using a session variable and it returns all the results that are associated with the logged in user.
Below is the php code i used to get the results.
<?php
session_start();
include('conn.php');
if(!isset($_SESSION['40219357_user'])){
header('Location:index.php');
}
$username = $_SESSION['40219357_user'];
$userid = $_SESSION['40219357_id'];
$read = "SELECT * FROM medi_users WHERE dr_id = '$userid'";
$result = $conn ->query($read);
?>
The result of this query is displayed in a table on my website. When the logged in user of the website clicks on a person's record it should show all the information relating to that specific person.
Since asking my original question i have found a simple solution to my problem by passing the user id as a hidden value in a button. The code for this is below.
<?php
while($row = $result ->fetch_assoc()){
$rowid = $row['id'];
$firstname = $row['firstname'];
$surname = $row ['surname'];
$dob = $row['dob'];
$address = $row['address'];
$town = $row['town'];
$postcode = $row['postcode'];
echo"
<tbody>
<tr>
<td>$firstname</td>
<td>$surname </td>
<td>$dob</td>
<td>$address</td>
<td>$town</td>
<td>$postcode</td>
<td><a class = 'btn btn-danger'
href `='patientsmedication.php?editid=$rowid'>View</a></td>`
</tr>
";
}
?>
</tbody>
</table>
</div>
</div>
I fully understand that this is not a very secure way of doing this and i would be open to suggestions as to how to do this correctly as i am keen to learn.
<?php
session_start();
//I think you are already using PDO/Mysqli prepared statements
//in this file since you call $conn->query below
include('conn.php');
if(!isset($_SESSION['40219357_user'])){
header('Location:index.php');
}
//
$username = $_SESSION['40219357_user'];
$userid = $_SESSION['40219357_id'];
//so to make this secure use place markers and bind your params
$read = "SELECT * FROM medi_users WHERE dr_id = '$userid'";
//becomes:
$read = "SELECT * FROM medi_users WHERE dr_id = :userId";
$q = $conn->prepare($read);
$q->bindParam(":userId",$userId,PDO::PARAM_INT);
$q->execute();
//now you can fetch your result set and store it in a variable
$results = $q->fetchAll();
?>
then you can loop through the results with a foreach
echo "<table>
<tr>
<th>Heading 1</th><th.....
</tr>";
foreach($results as $row) {
$rowid = $row['id'];
//I'm not sure if this is the right id,
//you would need to confirm, I would think you want to have a user id, but obviously don't know the structure
//of your database - if this is the user (patient?)
//id then it's fine
$firstname = $row['firstname'];
$surname = $row ['surname'];
$dob = $row['dob'];
$address = $row['address'];
$town = $row['town'];
$postcode = $row['postcode'];
echo "<tr>
<td>$firstname</td>
<td>$surname </td>
<td>$dob</td>
<td>$address</td>
<td>$town</td>
<td>$postcode</td>
<td><a class='btn btn-danger'
href='patientsmedication.php?patientId=$rowid'>View</a></td>//or whatever the relevant id is
</tr>";
}
echo "</table">;
I'm sure there are mixed feelings about passing an id in the url - personally I am not a big fan but we do it where I work for read only situations, if you have enough other checks in place then the id on it's own isn't really very useful to anyone.
Now in patientsmedication.php you can get the patients id using $_GET['patientId']
<?php
session_start();
include('conn.php');
if(!can_view_patient_details()) {
header('Location:error_page.php');
exit();
} else {
$patientId = isset($_GET['patientId'])??0;
//if you aren't using php7 you won't have the null coalescing operator so use a ternary style like $var = cond ? A : B
//now do your query
$q = "SELECT * FROM yourtable WHERE patientId = :patientId";
$q = $conn->prepare($q);
$q->bindParam(":patientId",$patientId,PDO::PARAM_INT);
$q->execute();
//now you can fetch your result set and store it in a variable
$results = $q->fetchAll();
}
function can_view_patient_details() {
//this should return true or false
//you would need to design your own permissions checks,
//given the nature of your project I would think you would
//do a database call to confirm the user has the right access
//to the patient, but you may just check that the correct
//sessions are set, you'd have to decide what is most appropriate
}
?>
Then with your result you can create the page as you see fit - if you are going to use this page to update details I would suggest a form because you can use the $_POST method which doesn't show the information in the url - then I would suggest it goes through a controller to do all the correct checks for permissions, data types etc.
If you haven't got into MVC patterns (which is likely if you are just starting out) then at least direct your form to a separate script, and then return to this page with some feedback - either by a flag in the url or by setting a session message and echoing it out.
A couple of things worth noting are that I assume you are using PDO not Mysqli prepared statements, they are both fine but the syntax is slightly different and my answer only uses PDO also in PDO you no longer need to use semi colons on your place markers (:userId == userId) but I personally prefer it for readability when writing sql. Also your session names look like they have the user id in the name ( it might be an internal code though that means something though), but if it is the id it's not very scalable to set it up this way - it's more simple to just have a session called 'user' and give it the value of the id - otherwise how would you know the name of the session without looking up the user, which would defeat the object.
Hopefully this will point you in the right direction, I recommend reading up on PDO and MVC patterns

PHP If Statements With mySQL Results

The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>
In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);
2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.

Can you use $_POST in a WHERE clause

There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.

Use PHP to link to user profile

I want my php query to display the user name with a link to the user profile.
<?php
$get_items = "SELECT * FROM items WHERE category='test'";
$result = mysql_query($get_items);
while($item = mysql_fetch_array($result, MYSQL_ASSOC)){
$creator = $item['created_by'];
echo "<b>Seller: </b>"."<a href='userprof.php?id=$creator'>$creator</a>";
}
?>
Clicking on this link takes it to a user profile page that I created. But I want "userprof.php?id=$creator" to know which user to display the account information. Is this the best way to do this? How can I read the url and display the correct information?
<?php
$userId = $_GET['id'];
$sql = "SELECT * FROM user WHERE id = " . intval($userId);
$result = mysql_query($sql);
...
You are sending a GET variable.
$id = $_GET['id']; // Contains whatever was in $creator;
use $_GET for getting the variable from the URL.
like in your code you want to access the user profile then get the user id from url
like
http://localhost/test/user_profile.php?uid=2
here in the url uid is 2 thet is your userid.
you can get this id by using the code
$user_id = $_GET['uid'];
use this variable in your query.
OMG!! HORRIBLE PHP ABOUNDS! IT HURTS MY EYES!!
These people, none of them did both of the correct things:
ALWAYS FILTER USER INPUT!!
NEVER TRUST PHP ESCAPE FUNCTIONS, ESP NOT intval() and addslashes()!!
EVEN mysql_real_escape_string() HAS VULNERABILITIES AND SHOULD NEVER BE USED.
You should used prepared statements for everything in 2010.
Here it is the proper way:
<?php
if (!filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))
{
trigger_error('Invalid User ID. It must be an integer (number).', PHP_USER_ERROR);
exit;
}
$userId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = "SELECT * FROM user WHERE id = ?";
$pdo = new PDO('mysql:host=localhost;db=mydb', $dbUsername, $dbPassWord);
$statement = $pdo->prepare($sql);
$statement->execute(array($userId));
$result = $statement->fetch(PDO::FETCH_ASSOC);
That is 100% secure. I hope people neither vote me down nor tone down my answer. Bad code is so systemic, we just have to shout from the rooftops until the new guys start learning it correctly, otherwise PHP as a professional language is seriously harmed.

Categories