I created a PHP form which allows users to Register and Log in. Now I created another page named View.php that will show all the registered users in my MySQL database. The code I used was
while($row=mysqli_fetch_assoc($sql))...
and it displayed all the users successfully.
Now I created another PHP page which I named profile.php. I want to add a link from every result on view.php which will redirect to profile.php?user=(their username). But I don't know how.
In this line:
echo "<small><a href = 'profile.php?user=$them'>[View Profile]</a></small><br/>";
instead of using your fixed $them, just use $row['id']. Then you can fetch the user with that id in your profile.php file:
$id = $_GET['user'];
$sql = "SELECT * FROM users where id = $id";
Note that this code is prone to sql injection. I only posted it to make the idea easier to understand. See here how to do it right.
I do not know the code you are using to achieve the result but having something like :
$query = "SELECT * FROM database WHERE id=$id";
$query = mysql_query($query);
This will filter out the profile page according to the user id
In your view.php considering that you have a column named 'username' , change the following :
please not, it's preferably to put the ID column If you want to put the id column, simply change the $row['username'] to $row['id'] and the same in the query in profile.php
<?php
...
while($row=mysqli_fetch_assoc($result)) {
echo "---------------------<br/>";
echo "<b>".$row['fullname']."</b><br/>";
echo "<small><i>".$row['course']."</i></small><br/>";
echo "<small><a href = 'friends.php?user=".$row['username']."'>[View Profile]</a></small><br/>";
echo "---------------------<br/><br/>";
}
?>
And in your
profile.php
<?php session_start();
if($_SESSION['logged_in']==false) {
header("Location:login.php");
}
include("header.php");
?>
<html>
<head>
<title>View School-Mates</title>
</head>
<body>
<center>
<h1>My School-Mates</h1>
<small>View or Add them in your Trust List</small>
<br/><br/>
<hr>
</center>
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test_basic', "root", "");
$stmt = $dbh->prepare("SELECT * FROM USERS WHERE username= ?");
if ($stmt->execute(array($_GET['user']))) {
while ($row = $stmt->fetch()) {
//here you will have your row with all your username data
}
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
</body>
</html>
Please read more about PDO from here and how to do connections this is required because you get data from your $_GET variable, and thus you need to avoid for sql injection
Hopefully this is what you wanted, if not, please let me know so i can adjust the code
Related
I'm trying to create a SQL query that takes the values of an entire table and dumps them into an array that I can call based the value of a URL parameter.
The parameter passed into the url will be ?username=User1.
I need the query to filter results in the database that are related to the that user (for example - their name, email address, interests etc).
I want to then be able to store them in an array that I can use to call and display the values, for example;
<?php echo htmlentities($row['profiles']['username'], ENT_QUOTES, 'UTF-8'); ?>
<?php echo htmlentities($row['profiles']['location_city'], ENT_QUOTES, 'UTF-8'); ?>
I use the following PHP to set the $u variable in PHP
My SQL query so far is as follows
$query = "
SELECT
user_id,
username,
displayname,
displayage,
location_city,
language
FROM profiles WHERE username='$u'
";
I then use the following PHP code to try and pass the data into an array;
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
My full code for profile.php;
<?php $_GET['u'] = 'u'; ?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
id,
username,
email
FROM profiles WHERE username='$u'
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
?>
<?php include('header.php') ?>
<div class="pages navbar-through toolbar-through">
<div class="page" data-page="profile">
<div class="page-content">
<div class="content-block">
<div class="content-block-inner">
<p>Profile content will go here</p>
Go Back<br />
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php') ?>
Change profile.php file contents as shown below:
<?php $username = (isset($_GET['username']))? trim(strip_tags($_GET['username'])) : ""; ?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
user_id,
username,
displayname,
displayage,
location_city,
language
FROM profiles WHERE username = '$username'
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php include('header.php') ?>
<div class="pages navbar-through toolbar-through">
<div class="page" data-page="profile">
<div class="page-content">
<div class="content-block">
<div class="content-block-inner">
<p>Profile content will go here</p>
<?php foreach($rows as $row): ?>
<div>Username: <?php echo $row['username'] ?></div>
<div>Location: <?php echo $row['location_city'] ?></div>
<?php endforeach; ?>
Go Back<br />
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php') ?>
I am new to PHP and just wanting to make a basic page where i can see all the users in the database and delete them. I have come this far but it keeps on telling me that I have an i have and Undefined index: user_id and although it tells me that it has deleted the fields it has not deleted anything. Here is my code:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<div id="cms_container"><br>
<br>
<h1>MANAGE USERS<img src="images/three_column_grid_line.png" alt="line"></h1>
<p class="logout_btn">Back</p>
<?php
$tbl="users"; // Table name
$sql = "SELECT * FROM $tbl";
$result = mysql_query($sql, $connect);
while($rows = mysql_fetch_array($result)){
?>
<?php
echo $rows['user_id'];
echo $rows['user_name'];
echo $rows['user_password'];
?>
delete
<?php
}
?>
<?php
mysql_close();
?>
</div><!--cms_container-->
</body>
</html>
The page that it should link to that deletes the query:
<?php include_once "includes/connect.php";?>
<?php
$tbl="users";
$user_id= $_GET ['user_id'];
$sql="DELETE FROM $tbl WHERE user_id = '$user_id'";
$result = mysql_query($sql, $connect);
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='delete.php'>Back to main page</a>";
}else {
echo "ERROR";
}
?>
<?php
mysql_close();
?>
In delete_user.php you must get user_id
$user_id= $_GET ['id'];
because in your delete link GET variable is "id", not "user_id"
You really should be using PDO instead.
The issue is in the information that you are passing.
The link : delete
is looking for an 'id' but you're later looking for 'user_id'
If you change it to delete, it should work.
I still strongly suggest you look into PDO instead though, it's much more secure and easier to work with.
Example of PDO Delete
public function deleteUser($username, $user_id){
if($this->isAdmin($username) == true){
$query = $this->db->prepare('DELETE FROM users WHERE user_id = ?');
$query->bindValue(1, $user_id);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}else{
return false;
}
}
I'm running an extra check to make sure the person who is requesting the deletion is an admin member but you should be able to see the structure
In addition to the other answers:
It looks like this line could be a fatal error, if php short tags aren't enabled:
delete
The php manual says:
*PHP also allows for short tags <? and ?>
(which are discouraged because they are only available if enabled with
short_open_tag php.ini configuration file directive, or if PHP was configured
with the--enable-short-tags option.*
http://php.net/manual/en/language.basic-syntax.phptags.php
The SQL query will be successful even if it alters zero rows. You are prefixing your user ids with a space when you are generating your HTML (id= <?), so you aren't matching any rows (since "1" won't be matched by " 1").
Where you are creating your 'Delete' link
delete
You're creating a variable of 'id', but later you look for 'user_id.
Change your link to
delete
i am making my own php game. So far i have made almost everything. Now to finish it, i need to get id from user who is logged in. I'm not so familiar with the functions and sessions. Please help.
This is what i made so far:
In my index page people login. then they are redirected to this.
So $_POST['username'] is where user type his user name in index.
<?php
$username = $_POST['username'];
include("Files/config.php");
$connect = #mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if($connect) {
if(mysql_select_db(DB_NAME)) {
$sql = mysql_query("SELECT * FROM users WHERE `username`='$username'") or die(mysql_error());
$gatherinfo = mysql_fetch_array($sql);
global $getid;
$getid = $gatherinfo['id'];
echo $getid;
function getuid() {
$_SESSION['getuid'] = $getid;
echo $getid;
}
}
}
else{ echo "Can not connect";}
?>
I searched other scripts for this, i found on one it says just $session->uid and it shows his id from mysql.
In mysql database i have table users with info about them
Id, username, password (password is hashed), email,...
Please help me if you can :D
At the beginning of index file (where your user logging in) start named session (be careful to avoid echo or print any values before session_start:
<?php //index.php
session_name('SAMPLESESSION');
session_start();
then when you will get the logged User ID, write this value to the session variable, like this:
.....
$_SESSION['uid'] = $getid;
.....
in the script you was redirected by your index file start session with the same name and get your user ID:
<?php //redirectedfromindex.php
session_name('SAMPLESESSION');
session_start();
echo $_SESSION['uid'];
....
If I right understand you, these that you need.
I made a small login system for users, they can log in and change their userinformation on the account_setting page.
But since im pretty new to php I wonder how can I give each user their own page? A page that is public.
Ex, User "Steven" has user_id=17.
How can I create a page for that user, so his information gets displayed there.
Something like website.com/user=17 ... His information.
And also if the page could act as a template, just diffrent information/url depending on user.
Im not asking anyone to write this for me, a link to a good tutorial would work just fine :)
But please, no 5year old posts on the topic.
you need userprofile.php?userid=17 and use $_GET['userid'] to draw the information based on that user. HTML should be same on userprofile.php only data will change depending on the user id. If userid is not set then show an error message or something
Generally saying:
if (!empty($_GET['user']) && is_numeric($_GET['user'])){
//Find him in database
if (user_found($_GET['user'])){
include "left_column.php" ;
include "user_info.php" ;
} else {
echo "Page is not found" ; //or set header error 404
}
} else {
include "news_column.php" ;
}
website.com/index.php?user=17
<?php
require_once 'db/connect.php';
//Pull in 'user' from the query string.
$user = isset($_GET['user']) ? trim($_GET['user']) : null;
//Try to pull that user's info from the database.
$stmt = $dbh->prepare("SELECT * FROM user WHERE user_id = :user_id");
$stmt->bindParam(':user_id', $user);
$stmt->execute();
$user= $stmt->fetch(PDO::FETCH_ASSOC);
if(!is_array($user)){
//User not found. Throw 404 or redirect.
header('HTTP/1.0 404 Not Found');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo htmlentities($user['name'], ENT_QUOTES, "utf-8"); ?></title>
</head>
<body>
<h1><?php echo htmlentities($user['name'], ENT_QUOTES, "utf-8"); ?></h1>
<p>
<?php echo nl2br(htmlentities($user['bio'], ENT_QUOTES, "utf-8")); ?>
</p>
</body>
</html>
I'm going to assume that you're storing your user information in a database. For the sake of argument, we'll say it's a mysql database. What you need to do is capture the userid and then read only that column from the database.
If your URL is website.com/user/view.php?id=17, your user variable will be in $_GET['id']
So something like this:
$id = mysqli_real_escape_string($_GET['id']);
$results = mysqli->query("select * from users where id = '$id'");
$results = $results->fetch_assoc();
... will bring up the information for the user; then you just build a page to display it.
I have this code which permits me to pass a variable to another page, but the problem is i cannot seem to get that variable using the link. We have tried before, this same method and has worked.. could you please check it?
Thanks..
The link:
$sql="SELECT * FROM pianificazione";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['job'] ?>
<?php echo '</br><br />'; }
?>
The page after the link:
include('menu.php');
$id=$_GET['job_id'];
$sql="SELECT * FROM attivita WHERE job_id='$id'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['attivita_da_promuovere'] ?>-<?php echo $row['attivita_tip_merc'] ?>-<?php echo $row['attivita_da_svolgere'] ?>-<?php echo $row['attivita_tip_personale'] ?>
You should be using:
$id = $_GET['id'];
You're also open to SQL injections... Either parse it as an INT:
$id = (int) $_GET['id'];
... or use prepared statements with PDO (instead of the default mysql functions that you're using, which are no longer recommended).
You're passing it as:
lista_attivita.php?&id=<?php echo $row['job_id'] ; ?>
And then looking for it as:
$id=$_GET['job_id'];
You should use:
$id=$_GET['id'];
In the URL that you're passing to the "page after link" you're setting "?id=xxx" as the parameter however in your script, your looking for "job_id".
Change the parameter to ?job_id= in your first script.
Two things.
1) FUNCTIONALITY
$id=$_GET['job_id'];
should be
$id=$_GET['id'];
since your link passes the variable id, not job_id:
lista_attivita.php?&**id**=<?php echo $row['job_id']
2) SECURITY
Never, NEVER insert user-input data directly into a SQL query. You are asking for headaches or worse. The $id on your receiving page should be validated and escaped prior to doing any lookup. If you expect a number, do something like this on the receiving page:
if (!is_numeric($_GET['id']))
{
// throw error
}
It's not a bad idea to query your DB for valid codes, put those in an array, then check that array to see if the passed value is found. This prevents user entered data from reaching your DB.
Something like this:
$q = "SELECT DISTINCT(id) FROM my_table WHERE display=1 ORDER BY id ASC";
$res = mysqli_query($dbx,$q);
while (list($_id) = mysqli_fetch_array)
{
$arr_valid_id[] = $_id;
}
Then,
if (in_array($_GET[id],$arr_valid_id[])
{
// do stuff
} else {
// throw error
}