Use PHP to link to user profile - php

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.

Related

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

Display particular loggedin user name

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.

My poll has a 'back button' loophole

Have had a couple questions answered very nicely here and I've got some more trouble someone can probably help with:
I have SQL database that holds a poll question answer and a user IP address. Here is my (now working!) PHP code:
// check to see if user has already voted
$current_user = $_SERVER['REMOTE_ADDR'];
$select_query = "SELECT * FROM w_poll_counter WHERE user_IP = '" . $current_user ."';";
$result = mysql_query($select_query);
if($result)
{
$row = mysql_fetch_array($result);
$user_from_db = $row['user_IP'];
if($current_user === $user_from_db)
{
//user already voted - show results page
header("Location: scripts/show_results.php");
exit();
}
}
The code works great, except there's one problem... After a user votes and sees the results page, they can click the browser's 'back' button and then simply vote again, since the code to check their IP address doesn't run in that instance.
What do I need to do to fix this issue?
Thanks!
Check if the user has already voted before executing your update statement.
Also you should take better care, your script is very vulnerable to sql injections. https://stackoverflow.com/a/60496/3595565
I can show you this example of an implementation via pdo:
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8;', 'dbUser', 'dbPassword');
$stmtCheck = $pdo->prepare("SELECT * FROM w_poll_counter WHERE user_IP = ?");
$stmtCheck->execute(array($_SERVER['REMOTE_ADDR']));
$result = $stmtCheck->fetchAll(PDO::FETCH_ASSOC);
if(count($result) === 0){
//update
}

Problems updating MySQL, "username" in a table using PHP

I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.

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.

Categories