if statement to determine $_SESSION data - php

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
?>

Related

MySQL PHP - Fetch data and present in HTML

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.

Querying another table after login

This seems like it should be simple, but I've tried it every which way and can't seem to get it to work.
I have this login script which I adapted from an online tutorial. What I'd like to do is have users sign in with a username and password, and if these are correct, have it go after their lab results in another table (same database) and display them. I can get it to sign in, but that's it. Here's the login code:
<?php //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
/*This is where I'm assuming the new query needs to go.
Query a different table named "data" and pick out information according to
$username which was put in earlier */
echo "<br><a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password   :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div><?php }
?>
</body>
</html>
A "Join" is what I get when I google it but that doesn't seem right. Could someone help?
You can just use a different query for making it easy:
$sql = mysql_query("SELECT * FROM data WHERE user = '" . mysql_real_escape_string($username) . "'");
Then you can process with this.
Please note that you should not use MySQL driver as it is deprecated, use MySQLi(mproved) instead. And you should escape the POSTed values, this is very important!
Your last else statement is trying to echo the HTML.
You should be using mysqli or PDO since mysql is deprecated.
<?php //Start the Session
session_start();
// require('connect.php');
// Establish connection with database
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `people` WHERE username='$username' and password='$password'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
echo "Valid";
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
echo "Username: $username";
echo "Session Username:".$_SESSION['username'];
// This is where I'm assuming the new query needs to go.
// Query a different table named "data" and pick out information according to $username which was put in earlier
echo "
Logout";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="test.php" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div>
</body>
</html>

Linking to user profile through PHP

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

How To Edit Single Record From Database?

Code as of 20 January 2014
<?php
session_start();
// connect to the database
include('connect.php');
$message = $_GET['message'];
// check if the form has been submitted then process it
if (isset($_POST['submit']))
{
// Get data from table
//set the id manually for test purposes
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check for empty fields and display error message
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
$message = "Please enter data in all fields" ;
header("Location: edit.php?message=$message");
}
else
{
// save the data to the table
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
}
// redirecr and display message
$message = "Your changes have been saved";
header("Location: edit.php?message=$message");
exit;
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from the table
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
print $message;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/forms.css" />
<script type="text/javascript" src="javascript/jquery-1.7.1.min.js"></script>
<link href='//fonts.googleapis.com/css?family=Cantora+One' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Ubuntu:400,500' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
</head>
<div class="container">
<form action="" method="post" enctype="multipart/form-data" name="edit" id="editrecord">
<fieldset>
<legend><span class="headingreg">Edit Details</span></legend>
<div class="formreg">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<br style="clear:left;"/>
<label for="forename">Forename</label><div><input type="text" id="forename" name="forename" class="insetedit" value="<?php echo $forename; ?>"/><br/></div>
<label for="forename">Surname</label><div><input type="text" name="surname" class="insetedit" value="<?php echo $surname; ?>"/><br/></div>
<label for="forename">Username</label><div><input type="text" name="username" class="insetedit" value="<?php echo $username; ?>"/><br/></div>
<label for="forename">Password</label><div><input type="text" name="password" class="insetedit" value="<?php echo $password; ?>"/><br/></div>
<label for="forename">email</label><div><input type="text" name="email" class="insetedit" value="<?php echo $email; ?>"/><br/></div>
<input type="submit" name="submit" class="submit2" value="submit">
</div>
</fieldset>
</form>
<br style="clear:left;"/>
<br style="clear:left;"/>
</body>
</html>
INDENTS REMOVED
I am following a tutorial for editing and deleting stored records in a database.
http://www.falkencreative.com/forum/records/view.php
In the tutorial one page displays the records in a database and another is used to edit the records :
http://www.falkencreative.com/forum/records/edit.php?id=33004
The problem is all the records in the database are displayed. What changes do I need to make so that I can display and edit a record based on a specified id on a single page? e.g.
$id = "429";
Eventually I will use sessions but for testing purpose I want to set the id manually.
I tried putting the code in a single page but got numerous errors e.g. headers already sent.
Here's the edit.php page with my attempt to set the id manually.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $forename, $surname, $username, $password, $email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Forename: *</strong> <input type="text" name="forename" value="<?php echo $forename; ?>"/><br/>
<strong>Surname: *</strong> <input type="text" name="surname" value="<?php echo $surname; ?>"/><br/>
<strong>Username: *</strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
<strong>email: *</strong> <input type="text" name="password" value="<?php echo $password; ?>"/><br/>
<strong>password: *</strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check that forename/surname fields are both filled in
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $forename, $surname, $username, $password, $email, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE login SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
// show form
renderForm($id, $forename, $surname, $username, $password, $email, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
And the view.php page :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM login")
or die(mysql_error());
// display data in table
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Forename</th> <th>Surname</th> <th>Username</th> <th>eMail</th> <th>Password</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['forename'] . '</td>';
echo '<td>' . $row['surname'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['password'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
REMOVED FUNCTION AND ERROR VARIABLE
<?php
include('connect.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check empty fields
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
echo 'ERROR: Please fill in all required fields!';
}
else
{
// save the data to the database
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// Redirect
echo "Your changes have been saved";
header("Location: edit.php");
}
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
echo 'formatting is messed up';
}
?>
You will just need to replace the $_GET['id'] with the code that provides the id.
If you are using sessions for example, replace $_GET['id'] with $_SESSION['id']
In your code from the file edit.php:
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
Change to:
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
Of course, in order to get to the point of executing that code, you would need to remove the conditional statements, since you are no longer getting the information from the $_GET.
I also added a LIMIT 1 to the query, so that you only return one record; you probably would anyway, but if id didn't have a unique index (such as a primary key), it may return multiple records.
Also, in this example, you could nearly replace all of the deprecated mysql_ references with mysqli_. It won't protect you the way mysqli can with prepared statements, but it still should work.
Finally, the renderForm function is a poorly formed function. You can only have one <html> declaration per page, and if you called the function more than once, it would have multiple declarations.

script not working on the server but works fine on the localhost

i have a problem with my script,i made a login script where you enter the username and password and its working perfectly on my localhost(i.e i can login in and out having access to the admin panel) i then uploaded it on my server but the confusing part is that when i try to log in with the right username and password its not accessing the admin panel and showing me the access denied message its like the session is not being set on the server while its perfectly working on my local host.. secondly i created a news page where i can view the news its also showing that there an no posts to show but on the localhost everything is perfectly working
this is my home.php where i enter the username and password
<?php
if(isset($_COOKIE['testsite'])){
header('Location: enter.php');
}else{
echo"
<html>
<head>
</head>
<body>
<center>Please login...</center>
<div align='center'>
<form method='post' action='login.php' id='generalform'>
<table border='1' width='25%'>
<tr><td>Name: </td><td><input type='text' name='name' maxlength='15'/></td></tr><br />
<tr><td>Password: </td><td><input type='password' name='password' maxlength='15'/></td></tr><br />
<tr><td>Remember me?: </td><td><input type='checkbox' name='remember'/></td></tr><br />
</table>
<p>
<input type='submit' value='login' /><p>
</form>
<a href='index.htm'>Back To Main Page</a>
</div>
</body>
</html>";
}
?>
and this is enter.php where its being accessed
<?php
session_start();
if(isset($_SESSION['name'])||isset($_COOKIE['testsite'])){
include('session.php');
}else{
echo "Access denied!";
}
?>
and this is my news.php it seems like the squery is not being accessed from the database i reall do not know whats wrong because on the locahost its working perfectly
<?php
include ('connect.php');
$query = "SELECT id, title, author, post, DATE_FORMAT(date, '%M %d, %Y') as sd FROM news_posts";
$result = #mysql_query($query);
if ($result) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url = 'comments.php?id='.$row['id'];
echo '<p><b>'.$row['title'].'</b><br />
'.$row['sd'].'<br />
Posted by : <b>'.$row['author'].'</b><br />
'.$row['post'].'<br />
Add new comment or view posted comments</p>';
}
} else {
echo 'There are no news posts to display';
}
?>
this is the login.php
<?php
session_start();
if($_POST){
$_SESSION['name'] = $_POST['name'];
$_SESSION['password'] = md5($_POST['password']);
if($_SESSION['name'] && $_SESSION['password']){
mysql_connect("localhost", "root", "nokiae71") or die("problem with connection...");
mysql_select_db("testsite");
$query = mysql_query("SELECT * FROM users WHERE name='".$_SESSION['name']."'");
$numrows = mysql_num_rows($query);
if($numrows != 0){
while($row = mysql_fetch_assoc($query)){
$dbname = $row['name'];
$dbpassword = $row['password'];
}
if($_SESSION['name']==$dbname){
if($_SESSION['password']==$dbpassword){
if(($_POST['remember']) == 'on'){
$expire = time()+86400;
setcookie('testsite', $_POST['name'], $expire);
}
header("location:enter.php");
}else{
echo "Your password is incorrect!";
}
}else{
echo "Your name is incorrect!";
}
}else{
echo "This name is not registered!";
}
}else{
echo "You have to type a name and password!";
}
}else{
echo "Access denied!";
exit;
}
?>
thanks in advance

Categories