How to set $_POST[''] to data from mysql_fetch? - php

I have the code below that lists all of the data from columns: Firstname & Surname, I also want it so that when they are clicked it takes you to a "profile" page where you can see the rest of their data. I have made a link directly to the profile.php page and before it I set it so that $_POST = id, I'm hoping to have it so that the $_POST['id'] will be changed to the users when they click on the link.
<?PHP
$result = mysql_query("SELECT id, firstname, surname FROM members WHERE createdby = '" . $_SESSION['myusername'] ."'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysql_fetch_row($result))
{
$id=$row[0];
$_POST['id'] = $id;
echo ("<a href=profile.php>".$row[1]." ".$row[2]."</a></br>");
}
?>
It loads the page up fine and all works just it's not setting $_POST to $id.
EDIT: I'm now using $_GET["id"] which works, but it only echoes out that value I can't use it in a query:
$id=$_GET["id"];
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);

Setting a value for $_POST["id"] will work on that very page but it does not mean that when you redirect to another page after that then your $_POST value will be automatically sent to that page. Rather you can try $_GET for this purpose. You can modify your link to be like
profile.php?id=$id
and on your profile.php page you can use $_GET["id"] rather than $_POST

Use session in place of post -- $_SESSION['id']

Related

PHP database user selection

Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['email'] . "<br />";
echo $_SESSION['username'];
}
// Close the database connection
mysql_close();
?>
I'm thankful for the help !
You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
session_start();
$_SESSION['id'] = the_id_of_your_logged_username;
}
Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";
In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.
Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"
Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);

Retrieving data from MySQL database using $_SESSION username

I am new at PHP and I'm trying to create a profile page whereby the user is able to view their information which they inserted when signing up to the website.
At first I'm attempting this with just their first name, so that whoever is logged in can see what first name they have saved on the database.
I have a included "checklog.php" page which includes
<? php session_start(); ?>;
And in my page, when i use;
echo $_SESSION['username']
The user's username is printed out fine.
So i've tried to apply this in mysqli query in order to print out their first name from the database like this;
<?php
if($db_server){
$query = "SELECT firstname FROM users WHERE username=$_SESSION['username']";
$result = mysqli_query($db_server, $query) or
die(mysql_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
echo $row['firstname'];
}
}
mysqli_free_result($result);
?>
But I get an error on line 15 which is the SQL statement, can someone tell me what I'm doing wrong in my statement?
First of all add session_start(); in the top of the PHP code..
<?php
session_start();//<-- Here
Second.. rewrite your query like this..
$query = "SELECT firstname FROM users WHERE username= '".$_SESSION['username']."'";

show row data from a specific ID

I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);

how to do URL abstraction in PHP

When i try to pass values in href
$query_string =
'id=' . urlencode($id) .
'&name=' . rawurlencode($name) .
'&dob='. $dob .
'&email='. rawurlencode($email);
print "<a href='update.php?$query_string'>Update Details</a>
<br>Student ID: $id
<br> Student Name: $name
<br> Date Of Birth: $dob
<br> Email ID: $email
<br>";
I can see the url as this in the address bar:
localhost/student_portal/update.php?id=abc&name=Giridharan%20Rengarajan&dob=1993-07-22&email=rgiridharan.93%40gmail.com
in the update.php i am updating the values in the database with respect to the id mentioning in the link
$sql="UPDATE student_details SET student_name='$name',student_dob='$dob',student_emailid='$email' WHERE student_id='$id'";
echo $sql;
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)==TRUE){
$_SESSION['updateflag'] = 1;
header("location:index.php");
}
So if i change the id in the link the details of the another user is updated. I want to avoid this.
Check to see if the user ID is associated with that email first.
$db->query("SELECT id FROM student_details WHERE student_id='$id' AND student_emailid='$email'");
if ($db->numRows()) {
// do update here
}
Alternatively, you can do:
SELECT id FROM student_details WHERE student_emailid='$email' and update that ID.
Finally, use POST and bind your params as others have suggested. (If you F5 the page, it'll update again if the action is GET. POST is marginally more difficult to tamper with, but should NOT be relied upon as a security measure in itself.)

$_get not working

i created update code for updating password in a table using id.This is the url from where i am getting id using $_GET but its not working.
http://www.example.com/en/resetPaSS.php?id=1&token=779d2aa48de104db46d66e29de576aac
The code:
if(isset($_POST['sub']))
{
$pass_hash = PassHash::hash($_POST['pass']);
$sql = "UPDATE user SET password='$pass_hash' WHERE id='$_GET[id]'";
$resu = mysqli_query($link,$sql);
//echo $sql;
if(!$resu)
{
$error="Unable to change Password. Try Again!";
}
else
{
echo"changed";
}
}
I also echo $sql and it shows UPDATE user SET password='$2a$10$bed9ad8e6cb910e0f1f12uXJldZLQ79f5HVrIiIAIZeZ9088Rre9.' WHERE id=''
Also tried $_REQUEST but still not works.
EDIT:
I am using this url for reseting password to send to the user which is created using
http://www.example.com/en/resetPaSS.php?id=$id&token=$token
try this:
$sql = "UPDATE user SET password='$pass_hash' WHERE id='" . mysqli_real_escape_string($_GET['id']) . "'";
If you use a form, then the id is not in the action url. You can also post the id by using a hidden input field
You must use prepared statement to prevent sql injection:
$sql = "UPDATE user SET password='?' WHERE id=?";
$stmt = $link->prepare($sql);
/* bind parameters */
$stmt->bind_param("si", $pass_hash, $_GET['id']);
/* execute query */
$stmt->execute();
EDIT
By clicking the link you will be go to your page where a form is. You have to edit the the id to the form or action url to make your script working by doing the following steps
make a variabele named id like this:
$id = isset($_GET['id']) ? $_GET['id'] : $_POST['id'];
also add hidden field to the form:
<input type="hidden" name="id" value="<?php echo $id; ?>">
Change the query bind_param to:
$stmt->bind_param("si", $pass_hash, $id);
If you know, that id is number, do this:
$id = intval($_GET['id']);
$sql = "UPDATE user SET password='$pass_hash' WHERE id='$id';";

Categories