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
Related
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.
I really got a problem now. I tried for decades and I can't find why it is not working. I want to get the user that is logged in to see their email on a specific page. I tried a new code now and i get this error: Notice: Undefined variable: row in
The code I use is:
<?
$username = $_SESSION['username'];
$sql = "select * from users where username=" . $username . "";
echo $sql;
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
}
?>
AND
<?php echo $row['email']; ?>
<?php
$username = $_SESSION['username'];
$query = mysql_query("select * from users where username='".$username."'");
while ($row = mysql_fetch_array($query)) {
$email=$row["email"];
}
echo $email;
?>
try this.
don't use mysql_* functions
I think... Problem is in SQL query. I propose your column "username" is something like VARCHAR(50). So you have to add quote.
$sql = "select * from users where username='" . $username . "'";
I see a bug, and a design problem.
You've designed your script so that you're printing whatever was last assigned to $row in the condition of your while loop.
You're getting the error because the query is not returning anything and the loop is not running. Therefore, $row is never assigned. That being said, you probably don't want to use a while-loop if all you're trying to do is display the value of the "email" column in the first record returned. If you did want to, then stop it.
Call mysql_fetch_assoc() on your $result (doesn't return as much data), and check that it doesn't return FALSE (one or more records weren't found).
if((row = mysql_fetch_assoc($result)) === false)
die("Error.");
?>
Email:
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.
I have the following code in view.php, I would like to take the information to edit.php without compromising on security or show what is contained in the variables. edit.php has a form to edit the information from the database.
while ($row = mysql_fetch_assoc($result))
{
echo "" . $row['first_name'] ." " . $row['surname'] . "";
echo "<br />";
}
You are already compromising in security - see SQL injection and escaping strings.
Also, it is common practice to include other modules of the application by requiring (see require_once() and require() functions) files. It itself is not a security vulnerability, but indeed encloses all the global variables, functions and classes to that script.
If you really need that, you can unset (see unset()) all the variables you have set, but leave only data you want to be passed.
Learn how to write clean and secure code and it will be secure. Including one PHP file into another is not an insecure practice.
EDIT:
Some start may be creating classes with private or protected properties and public methods, then using them to store sensitive information and execute some actions. By using encapsulation you may achieve what you need.
You should allow only logged in users to see or edit that information, also you might get an SQL injection with:
$first_name = $_POST['first_name'];
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
You should have instead:
$first_name = mysql_real_escape_string( $_POST['first_name']);
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
The best way to do this would be(assuming you cant do anything else other than to use a standard anchor link to pass the variable) have an md5 of id of each of your record in the table. So that you can do
while($row = mysql_fetch_assoc($res))
{
echo "" . $row['first_name'] ." $row['surname'] . "";
}
now in edit.php retrieve this and compare it with the hash.
An even more secured way would be to concatenate the id of the record with another unique data such as join date or dob and hash the entire string. It would be highly secure that way.
Option 1: Just past the id from the database via your link. If user knows the id, but doesn't know any other information, than it's useless to it. Using something else will just bring few more code lines.
Option 2: Set user's id in SESSION
$first_name = mysql_real_escape_string( $_POST['first_name']);
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['first_name'] = $first_name;
Then to set other values from the database as session variables, e.g. the user's surname:
$_SESSION['surname'] = $row['surname'];
Then from any other page you can do
if ($_SESSION['loggedin'] == true) {
echo "Welcome $_SESSION['first_name'] $_SESSION['surname']!";
}
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.