On my website I've displayed a list of registered users on a members page using echo in PHP. I'd now like to link the names of these users to their profile pages. Is there a way to do this?
My current code:
<html>
<title>Find User Info</title>
<body>
<form method="POST">
<p>Type Username: </p><input type="text" name="username"placeholder="Enter Username...">
<br>
<input type="submit" name="submit" value="Search User">
</form>
<?php
session_start();
error_reporting(0);
$connection = mysql_connect("localhost", "root", "***"); // Establishing Connection with Server
$db = mysql_select_db("****", $connection); // Selecting Database from Server
$query = mysql_query("SELECT * FROM accs ORDER BY loginstatus"); //selecting all from table users where username is name that your is loged in
while($row = mysql_fetch_assoc($query))
{
echo $row['name'];
}
if(isset($_POST['submit'])){
$username = $_POST['username'];
$_SESSION['searchuser'] = $username; //setting session username to one from table, this is useful if you login, that restart your browser and than you go in url where is your profile.php... Anyway this is useful :D
header( 'Location: user.php' ) ;
}
?>
</body>
</html>
The template link is like: mywebsite.com/search/user.php
echo ''.$row['name'].'';
is this what you are looking for ?
All you'll have to do is echo out an <a> element with the appropriate parameters for the link.
In your loop where you echo out the name of the user. you can include the <a> element definitions and only have the name as the text of the link:
while($row = mysql_fetch_assoc($query)) {
$user_name = $row['name'];
$profile_link = "http://your-cool-site/users/" . $row['id'];
echo "<a href='" . $profile_link . "' >" . $user_name . "</a>";
}
This code assumes that the link to your user page is something like:
http://your-cool-site/users/USER_ID
Related
I have created a customer database in which 4-5 staff will have access to login to view, edit and delete records.
I need the html table that lists the customer records to show an 'Edit' and 'Delete' link only when the logged in userID ($_SESSION[userID]) matches the userID of who created the record. So, if a staff member created 3 out 5 records, they should only see an 'edit' and 'delete' hyperlink against these three records, and nothing on the other two.
I have managed to get to the point of the sessions working - however, being new to PHP I am not sure where exactly to put my IF statement to echo the 'Edit' and 'Delete' links - and completely lost in how to write it exactly. I have tried many attempts, but am tearing my hair out now! Any help will be hugely appreciated.
This is my session start file (authenticate.php):
<?php
session_start();
$_SESSION["staffID"] = "staffID";
?>
Staff login file (staff_login.php):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Staff login</title>
</head>
<body>
<?php
require("db.php");
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking if user existing in the database or not
$query = "SELECT * FROM `staff login` WHERE username='$username'
and password='$password'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION[staffID] = $rows["$staffID"];
// Redirect user to edit_contact.php - was index.php -
header("Location: edit_contact.php");
}
else
{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='staff_login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Staff login</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
And the php file to show the records in a table with the 'Edit' and 'Delete' hyperlinks:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit contact</title>
</head>
<body>
<h2>Tate Finance Customer contact details</h2>
<?php
//***edit_contact.php***///
// Developed by: []
// Contact: []
// Created: [November 2018]
// Last Modified: [26 November 2018]
/* Purpose: This file lists all contacts from the mycontacts database in a table for logged in users to add, edit or delete their contacts.*/
//include authenticate.php file on all secure pages
require('db.php');
include("authenticate.php");
?>
<!--Add welcome note to staff user-->
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<p>Logout</p>
<h3>Add new customer</h3>
<?php
$con = mysqli_connect("localhost","root","xxxxxx","mycontacts");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// Show all contacts from database in a table list
$query = "SELECT * FROM contact ORDER BY conName ASC";
$rst = mysqli_query($con,$query);
if($rst)
{
if(mysqli_num_rows($rst)>0)
{
// Table design for contacts list
echo "<table border='1'><tr><td>Edit contact</td><td>Name</td><td>Address</td><td>Phone</td><td>Mobile</td><td>Email</td></tr>";
while ($row = mysqli_fetch_assoc($rst))
{
/* Present contacts details in table list according to id selected, with links to edit or delete according to contactID selected */
/* This is where I think my IF statement needs to go, but can't figure out how/what to write to make it work */
echo "<tr><td>Edit Delete</td><td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
echo "</table>";
}
}
else
{
echo "No results found";
}
}
?>
</body>
</html>
while ($row = mysqli_fetch_assoc($rst))
{
echo "<tr>";
if($_SESSION["staffID"] == $id_of_creator){
echo "<td>".
"Edit".
"<a href=delete_record.php?
id=".$row['contactID']."> Delete</a> ".
"</td>";
}else echo "<td></td>";
echo "<td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
<?php
while($row = mysqli_fetch_assoc($selectAllCustomer)){
$id = $row['customer_id'];
$name= $row['customer_id'];
$email= $row['customer_email'];
echo "<tr>";
if($_SESSION['staffID'] == $Admin_Id){
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
echo "<td>";
echo "<a href='editPage.php?edit='".$id."'>Edit</a>";
echo "</td><td>";
echo "<a href='deletePage.php?delete='".$id."'>Delete</a>";
echo "</td>";
}else{
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
}
echo "</tr>";
}
NB: the valiable $admin_Id, is a id of the creator
?>
I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.
I have local host website. Connected two devices to a hotspot and accessing the website using the ip of the server. All the pages open properly but the session variable is not recognised as "Undefined Index" error throws up.
While when I access the same on the localhost I donot face this issue.
I have used session_start() in all the files.
Have the code snipped of Login.php
<?php
session_start();
?>
<html>
<head><title>LOGIN</title></head>
<body>
<form action= "Dashboard.php" method = "POST">
<br/>Name: <input type = "text" name = "name">
<br/>Password: <input type = "password" name = "password">
<br/><input type="submit" name = "submit" value = "submit"> or Register
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$password = $_POST['password'];
$connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");
$query = mysqli_query($connect,"SELECT * FROM users WHERE Name = '$name' and Password='$password'");
$count = mysqli_num_rows($query);
if($count == 1){
$_SESSION['username'] = $name;
echo "Login Successful";
}else{
echo "Invalid Login Credentials";
}
}
?>
After login Dashboard.php
<?php
session_start();
?>
<html>
<head><title>Dashboard</title></head>
<body>
<form action= "" method = "POST">
<?php echo "Welcome ".$_SESSION['username'].".<br>";
?>
<br/>Sex: <select name="sex"> <option value ="Male">Male</option> <option value = "Female">Female</option></select>
<br/>Age: <select name="years">
<?php
for($i=1; $i<=50; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
<option name="years"> </option>
</select>
<br/>Citizen: <select name="citizen"><option value="Singaporean">Singaporean</option><option value="International">International</option></select>
Click to Download!
<br/><input type="submit" name = "submit2" value = "Save Changes"> orLogout
</form>
</body>
</html>
<?php
if(isset($_POST['submit2'])){
$name = $_SESSION['username'];
$connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");
$query1 = mysqli_query($connect,"SELECT Sex,Age,Citizen FROM users where Name = '$name'");
while ($row = mysqli_fetch_row($query1))
/* {
echo "Details Entered in Database:".".<br>";
echo "<br>";
echo "Name:".$_SESSION['username'].".<br>";
echo "Sex:".$row[0].".<br>";
echo "Age:".$row[1].".<br>";
echo "Citizen:".$row[2].".<br>";
}*/
$sex = $_POST['sex'];
$years = $_POST['years'];
$citizen = $_POST['citizen'];
$query2 = mysqli_query($connect, "UPDATE users SET Sex = '$sex', Age='$years', Citizen='$citizen' WHERE Name = '$name'");
echo "Saved changes";
}
?>
Please suggest
Your form has the action "Dashboard.php", so that script will handle the submission of your login form.
In other words, the logic inside the code block for the if statement if(isset($_POST['submit'])){ is probably not executed, so your session variable isn't set.
You can set the action to "Login.php" or leave it blank to let Login.php handle the login, then you can redirect to Dashboard.php if you desire and the session variable should be set.
Do mind that if you want to redirect using PHP, it must be done before the HTML. Otherwise it won't work.
On this page, volleyLogin.php, when the user hits it for the first time everything works well - they log in with their username and from there can go on to AddNew.php. When the user clicks 'Create' on AddNew.php, it goes back automatically to volleyLogin.php. The details of AddNew.php are saved to the mysql database, but on going back to volleyLogin.php we see :
http://screencast.com/t/esgXUJlMa
which is the line :
$sql = "SELECT * FROM user WHERE username = '$username'";
How can I fix this ?
Here's my code:
volleyLogin.php
<?php
require('dbConnect.php');
//if the session is already active, like we are coming back to this page from AddNew.php
if (session_status() == PHP_SESSION_ACTIVE) {
//session_start();
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
}
//if user is logging in
if(isset($_POST['username'])){
//helps stop sql injection
$username = mysqli_real_escape_string($con,$_POST['username']);
}
//select everything from user
$sql = "SELECT * FROM user WHERE username = '$username'";
//get the result of the above
$result = mysqli_query($con,$sql);
//get every other record in the same row
$row = mysqli_fetch_assoc($result);
//make the user_id record in that row a variable
$user_id = $row["user_id"];
$username = $row["username"];
echo "user id is " . $user_id . "<br>";
echo "user name is " . $username . "<br>";
session_start();
$_SESSION['user_id']= $user_id;
$_SESSION['username'] = $username;
$sql2 = "SELECT * FROM review WHERE user_id = '$user_id'";
$result2 = mysqli_query($con,$sql2);
//if username isn't in the db
if (mysqli_num_rows($result)==0) {
echo "Failed, sorry";
}
//if username is in the db
if (mysqli_num_rows($result) > 0) {
//if username has reviews in the db
while($rows = mysqli_fetch_assoc($result2)) {
$review_id=$rows['review_id'];
$_SESSION['review'] = $review_id;
echo "review id is " . $review_id . "<br>";
echo "<br>";
echo "Category: " . $rows['cat_name'] . "<br>";
echo "Name: " . $rows['name'] . "<br>";
echo "Phone: " . $rows['phone'] . "<br>";
//html stuff comes next
?>
<!-- show the + button, click for more details -->
<html>
<body>
<form action="showreview.php?id=<?=$review_id?>" method="post">
<input type="submit" value="+" name="show_review"><br>
</form>
<p></p>
</body>
</html>
<?php
}
?>
<html>
<body>
<form action="AddNew.php" method="post">
<input type="submit" value="Add New" name="username"><br>
</form>
</body>
</html>
<?php
}
$con->close();
?>
AddNew.php
<?php require('dbConnect.php');
//use the variables we created in volleyLogin.php
session_start();
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
echo "user name is " . $username . "<br>";
echo "user id is " . $user_id . "<br>";
if (isset($_POST['create'])) {
$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);
//in the review table, create a new id, put in the cat_id it comes under, the user id...
$sql2 = "INSERT INTO review VALUES(NULL,'666','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
if ($con->query($sql2) === TRUE) {
header('Location:volleyLogin.php');
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
}
}
$con->close();
?>
<!doctype html>
<html>
<body>
<h2>Create new Contact</h2>
<form method="post" action="" name="frmAdd">
<p><input type="text" name = "category" id = "category" placeholder = "category"></p>
<p><input type="text" name = "name" id = "name" placeholder = "name"></p>
<p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
<p><input type="text" name = "address" id = "address" placeholder = "address"></p>
<p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>
<h2>Visible to :</h2>
<input type="radio" name="allmycontacts" value="All my Contacts">All my Contacts
<input type="radio" name="selectwho" value="Select Who">Select Who
<input type="radio" name="public" value="Public">Public
<input type="radio" name="justme" value="Just me">Just me
<p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
Exit
</form>
</body>
</html>
Thanks for any help.
Hm, strange.
In my volleyLogin.php I have :
session_start();
$_SESSION['user_id']= $user_id;
$_SESSION['username'] = $username;
I simply took session_start(); out of there and put it right at the very top, after my opening
<?php tag and now it works correctly.
I am trying to implement a page where a user enters a comment and it gets displayed right in the same page. The problem i am having is that every time you go to the page there are no comments in the page(there are actually comments).
This is my sceneario i am having:
I go to the page and there are no comments, i enter a comment 'hello' and it gets displayed right away.
I go to a different page and then i come back to the comments page and there are no comments.(the comment "hello" should be already displayed)
I enter a comment "hi" and both comments "hello" and "hi" get displayed
I cant resolve this issue..
This is my code, its pretty long
<?php
session_start(); //starts or continues the session
require_once('functions.php'); //needed for some function calls
error_reporting(E_ALL ^ E_NOTICE);
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<script type = "text/javascript" src = "functions.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
GetUserLayout($_SESSION['userId'], $_SESSION['superUser']);
?>
<div id = "shareyouridea_form" class = "post">
<h1> Share your post</h1>
<!-- used for the form -->
<form id = "idea_form" method = "post"
action = "<?php echo $PHP_SELF;?>"
onkeypress = "return DisableEnterKey(event);">
<table>
<caption>
<strong>
<br /> Share post form:
</strong>
</caption>
<tr class = "spacearound"> <!-- input for bright idea -->
<td> Post: </td>
<td>
<textarea form = "idea_form" name = "b_idea" rows = "12"
cols = "85" title = "Please describe your product idea"
id = "bright_idea" maxlength = "1000"
onkeypress =
"return InputLimiter(event, 'lettersSpacePunctuation');">
</textarea>
</td>
</tr>
</table>
<p>
<input type = "reset" value = "Reset" />
<input type = "submit" value = "Share Idea!"
title = "complete form first to submit"
id = "submit_button"
name = "add_comment"
onmousedown = "IsIdeaFormCompleted();" />
</p>
</form> <!-- end idea_form -->
</div>
</div> <!-- end of ShareYourIdea_middle -->
<script>
DisplayFooter();
</script>
<?php
if(isset($_POST['add_comment'])){ // if add comment was pressed
// get variables
$name = $_SESSION['firstName'];
$empId = $_SESSION['userId'];
$idea = $_POST['b_idea'];
// CONNECTING TO OUR DATABASE
$db = mysqli_connect(dbHost, dbUser, dbPassword, dbName);
if (mysqli_connect_errno()) { //if connection to the database failed
echo("<p id = 'greatideadescription'>
Connection to database failed: " .
mysqli_connect_error($db) . "</p>");
exit("goodbye");
} //by now we have connection to the database
// WE WRITE OUR QUERY TO INSERT POST INFO TO DATABASE
$query = "INSERT INTO posts(postId,empl_Id,post,postDate)
VALUES('','$empId','$idea',NOW())";
$result = mysqli_query($db, $query);
}
?>
<?php
// WE DO A QUERY TO SHOW ALL COMMENTS IN THE PAGE
$query = "SELECT firstName,lastName, post,
date_format((date_add(postDate,interval -7 hour)),'%a, %M, %d, %Y at %I:%i%p' ) as mydatefield
FROM users INNER JOIN posts ON userId = empl_Id
ORDER BY postDate DESC";
$result = mysqli_query($db,$query);
if (!$result) { //if the query failed
echo("<p id = 'greatideadescription'>
Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);}
if (mysqli_num_rows($result) == 0) { //if no rows returned
echo("<div id = 'blogs'>
<div id ='name'>
No posts detected
</div>
</div>
<div class='fb-like' data-href='http://jacobspayroll.zxq.net/index/blog.php' data-send='true' data-width='450' data-show-faces='true'></div>
");
mysqli_close($db); //close the database
exit("</table></div></form></div></div>
<script>DisplayFooter();</script></body></html>");
} //by now we know that we have some products purchases returned
$numRows = mysqli_num_rows($result); //gets number of rows
$numFields = mysqli_num_fields($result); //gets number of fields
//prints the data in the table
while($row = mysqli_fetch_assoc($result)){
$posted = $row['post'];
$message = wordwrap($posted,5);
echo
'<div id ="blogs">
<table id = "blog_id">
</br>
<div id = "name">
<strong>'.$row['firstName'] . ' ' .$row['lastName'].
'</strong>
: ' .$message .
'<br/>
</div>
<div id ="date">'.
$row['mydatefield'] . '
</div>
<div id ="delete_comment">
Delete this comment
</div>
<p>
</table>
</div>';
}
mysqli_close($db);
?>
</body>
</html>
You have the wrong Usage of PHP_SELF
//You must use Server and execution environment information `$_SERVER[]`
$_SERVER['PHP_SELF'];
// For your form action like this
action = "<?php echo $_SERVER['PHP_SELF'];?>"
as Kail mentioned you got it wrong but you might want to use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF'] then you might want to add some script to get GET parameters if you use them for your script(s). If you use PHP_SELF you might have a user link to script.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E%3Cfoo might look like action="script.php/"><script>alert('xss')</script> or could be a redirect to collect cookies and the alike in other words XSS attack.
$_SERVER['PHP_SELF'] vs $_SERVER['SCRIPT_NAME'] vs $_SERVER['REQUEST_URI']
XSS Woes
What's the difference between $_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME']?