How to delete MySql database row with PHP button - php

I have an backend website setup that displays all the users on my site in an organised table, I should be able to edit and delete the users from the php page. However I cannot get the delete function to work, here is the code.
Data_Display.php
<?php
include('session.php');
?>
<?php include ("db.php"); ?>
<?php
$sql = "SELECT * FROM username ORDER BY UserNameID DESC";
$query = mysql_query($sql) or die(mysql_error());
if (isset($_GET['UserNameID'])) {
$id = mysql_real_escape_string($_GET['UserNameID']);
$sql_delete = "DELETE FROM users WHERE id = '{$UserNameID}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/ico" href="favicon.ico">
<title>Network TV - All Records</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body >
<div class="container">
<div class="content">
<h1>Network TV Users and User control panel</h1>
<br>
<div class="toolbar">
Add New Person
Home
</div>
<br>
</div>
</div>
<div class="container">
<div class="content">
<?php if (mysql_num_rows($query)) { ?>
<?php while ($rows = mysql_fetch_assoc($query)) { ?>
<div class="separator"></div>
<h2><b>User reference:</b> <?php echo $rows['UserNameID']; ?></h2>
<h2><b>Name:</b><?php echo $rows['name']; ?></h2>
<h2><b>Email address:</b> <?php echo $rows['email']; ?></h2>
<h2><b>Gender:</b> <?php echo $rows['sex']; ?></h2>
<h2><b>Profile Picture:</b> <?php echo $rows['imagelink']; ?></h2>
<div class="toolbar">
Edit
Delete
</div>
<?php } /* End Loop */ ?>
<div class="separator"></div>
<?php } else { ?>
<div class="separator"></div>
<h2>There are no records to display</h2>
<div class="separator"></div>
<?php } /* End Rows Checking */?>
</div>
</div>
<div class="container">
<br>
<br>
<br>
<br>
<br>
</div>
<script>
function confirmDelete ( message, url )
{
var confirmation = confirm ( message );
if ( confirmation == true ) {
window.location = url;
} else {
return false;
}
}
</script>
</body>
</html>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "Oliver");
// Selecting Database
$db = mysql_select_db("users", $connection);
if(!isset($_SESSION)){session_start();}
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from username where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: home.php'); // Redirecting To Home Page
}
?>
db.php
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver');
mysql_select_db('users', $connection) or die(mysql_error());
?>
Information
When I click the delete button in data_display.php, I do receive the javascript alert to confirm that I do want to delete the user from the database, but nothing actually happens.

if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM users WHERE id = '{$id}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
You are sending recordId as parameter.

Related

Deleting data from database using PHP

I am trying to delete data from MySQL using PHP
<?php
if (isset($_POST['delete'])) {
$queryDelete = "Delete FROM info WHERE userID={$_POST['delete']}";
if (!($database = mysqli_connect("localhost", "root", ""))) {
die("Could not connect to database. </body></html>");
}
if (!mysqli_select_db($database, "project2")) {
die("Could not open books database. </body></html>");
}
if (!(mysqli_query($database, $queryDelete))) {
echo "<p>Could not execute query!</p>";
die(mysqli_error($database) . "</body></html>");
}
mysqli_close($database);
}
this is my delete.php using it on this page
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Style.css">
</head>
<header>
<div>
<p id="page">Users List</p>
<img id="title_pic" src="images/title_pic.jpg" alt="#">
</div>
</header>
<body>
<?php include 'bar.php' ?>
<?php include 'delete.php' ?>
<br><br><br><br>
<h1 style="color:yellow;"> List of all Users: </h1>
<br>
<?php
$query = "SELECT userID, fName, email FROM info";
if (!($database = mysqli_connect("localhost", "root", ""))) {
die("Could not connect to database. </body></html>");
}
if (!mysqli_select_db($database, "project2")) {
die("Could not open project database. </body></html>");
}
if (!($result = mysqli_query($database, $query))) {
echo "<p>Could not execute query!</p>";
die(mysqli_error($database) . "</body></html>");
}
mysqli_close($database);
while ($row = mysqli_fetch_row($result)) {
foreach ($row as $value) {
echo "<span style='color:white;'> $value </span>";
}
echo ' <form action = "delete.php" method = "POST">';
echo '<input type="submit" name= "delete" value="delete" class="btn">';
echo '</form>';
echo "<br>";
}
?>
</html>
It's redirecting me to delete.php page but when I go back to the second one (Displayuser.php) all info are there and nothing is deleted
I used the same technique to add info but I am having trouble to delete them from the table.
Here is how your code should look like. First in your form, provide the ID of the user you want to delete. Make sure to enable mysqli error reporting and select the right database when connecting.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect("localhost", "root", "", 'project2');
$database->set_charset('utf8mb4'); // always set the charset
$users = $database->query("SELECT userID, fName, email FROM info");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Style.css">
</head>
<body>
<header>
<div>
<p id="page">Users List</p>
<img id="title_pic" src="images/title_pic.jpg" alt="#">
</div>
</header>
<?php include 'bar.php' ?>
<?php include 'delete.php' ?>
<br><br><br><br>
<h1 style="color:yellow;"> List of all Users: </h1>
<br>
<?php
foreach ($users as $user) {
foreach ($user as $value) {
echo "<span style='color:white;'>'.htmlspecialchars($value).'</span>";
}
echo ' <form action = "delete.php" method = "POST">';
echo '<button type="submit" name="delete" value="'.htmlspecialchars($user['userID']).'" class="btn">Delete</button>';
echo '</form>';
echo "<br>";
}
?>
</html>
Then in your delete.php, read the POST value and delete the row with that ID using prepared statement.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect("localhost", "root", "", 'project2');
$database->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['delete'])) {
$stmt = $database->prepare("DELETE FROM info WHERE userID=?");
$stmt->bind_param('s', $_POST['delete']);
$stmt->execute();
}

mySQL auto-increment + auto adjust id by dynamicly deleting table content via PHP?

I am currently trying to build a "ToDo-App" which lets me INSERT text into a database, which will then be displayed. There is a "feature" to delete content based on their ID.
If I input two tasks into my application, I get two table records with ID 1 and 2. When I delete record 1, the record with ID 2 still exists. Thus, the record with ID 2 is listed as the first item in the to-do list.
I have to enter "2" in the "delete input field" to delete the first item from the list! How can I get this to be in sync? Is the ID field appropriate for maintaining the logical / application level order of the tasks?
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
</head>
<?php
$con = mysqli_connect("","root","","todo");
$sql = "SELECT text FROM work";
$res = mysqli_query($con, $sql);
if(isset($_POST["text"]))
{
$eingabe = $_POST["text"];
$query = "INSERT INTO work(text) VALUES('$eingabe')";
mysqli_query($con, $query);
header("Refresh:0");
}
else
{
echo "";
}
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
else
{
echo "";
}
?>
<body>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<form action="index.php" method="post">
<input class="lil-input" name="text" type="text">
<input type="submit" class="lil-button-green" value="Hinzufügen">
</form>
<ol id="liste" class="lil-list">
<?php
while($dsatz = mysqli_fetch_assoc($res))
{
echo "<li>" .$dsatz["text"] ."</li>";
}
?>
</ol>
<form id="form" action="index.php" method="post">
<input class="lil-input" name="del" type="text">
<input type="submit" class="lil-button-red lil-button-small" value=" Löschen ">
</form>
</div>
</div>
</div>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
var anzahl = $("#liste li").length;
if(anzahl < 1)
{
$("#form").hide();
}
else
{
$("form").show();
}
</script>
</body>
</html>
The pictures:
HTML Output
MySQL Dashboard
As discussed in the comment, you can have multiple checkboxes forming an array parameter: <input name="theName[1]"> with explicit key and name="theName[]" with implicit keys.
Further more, you should use prepared statements to prevent SQL injection attacks. Imagine an attacker sends a request with a single quote ' in the field, i.e. he terminates the SQL string delimiter, and adds arbitrary SQL code. Prepared statements use placeholders and the parameters are sent separately.
You should also handle errors. In the code below errors are output as HTML, however, you should define your own logger function rather than just echo into the stream. This can output HTML on development servers but log to disk on production servers.
This is a working example tested on PHP7.3 with MariaDB 10:
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
<style>
#frm-tasks button
{
padding: 0 18px;
}
</style>
</head>
<body>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$con = new mysqli('localhost', 'testuser', 'testpasswd', 'testdb');
$action = $_POST['action'] ?? 'list';
if(!empty($_POST["text"]))
{
$eingabe = $_POST["text"];
try
{
$stmt = $con->prepare('INSERT INTO work(text) VALUES(?)');
$stmt->bind_param('s', $_POST["text"]);
$stmt->execute();
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
if('del' === $action && isset($_POST['rows']) && is_array($_POST['rows']))
{
try{
$stmt = $con->prepare('DELETE FROM `work` WHERE `work`.`id` = ?');
$stmt->bind_param('i', $row);
foreach ($_POST['rows'] as $row)
{
$stmt->execute();
if($e = $stmt->error)
echo "<div>DB Error: $e</div>";
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
?>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<!--form action="index.php" method="post"-->
<form id="frm-tasks" action="" method="post">
<input class="lil-input" name="text" type="text">
<button type="submit" class="lil-button-green" name="action" value="add">Hinzufügen</button>
<?php
try
{
$res = $con->query('SELECT id, text FROM work');
if(0 < $res->num_rows)
{
?>
<table>
<thead>
<tr>
<th></th><th>ID</th> <th>Aufgabe</th>
</tr>
</thead>
<tbody>
<?php
while($dsatz = mysqli_fetch_object($res))
{
?>
<tr>
<td><input type="checkbox" name="rows[]" value="<?php echo $dsatz->id;?>"></td><td><?php echo $dsatz->id;?></td> <td><?php echo $dsatz->text;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<button type="submit" class="lil-button-red lil-button-small" name="action" value="del">Löschen</button>
<?php
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $e->msg;</div>";
}
?>
</form>
</div>
</div>
</div>
<!-- not needed atm script src="js/jquery-3.3.1.min.js"></script-->
<h2>POST</h2>
<?php
var_dump($_POST);
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error connecting DB: $msg;</div>";
}
?>
</body>
</html>
The key of the list is the 'th' in the database so just fixing limits
Replace
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
With
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` LIMIT 1 OFFSET ".array_search($del, mysqli_fetch_assoc($res));
mysqli_query($con, $sql2);
header("Refresh:0");
}

How to display username in home.php page after login

I am a beginner. I dont have any professional degree on coding. I have learnt through internet only. I have developed a few pages which will be connected to database. I have tried to login using username and password and it successfully redirects to the home page. Now I want the username to be displayed on the home page after login. please help. what modifications do I need to do ??
login_save.php code is as below-
<?php
function SignIn($loginname,$pass) {
//require_once '../../common/createdbconn.php';
$login_id='';
$login_status='';
$error_message= '';
if(!empty($loginname) && !empty($pass)){ //checking the 'user' name and password, is it empty or have some text
$login_id=validate_login($loginname,$pass);
if ($login_id != '') {
$login_status=$login_id;
}
else {
//empty check
$error_message=NO_USERNAME;
$login_status=$error_message;
}
return $login_status;
}
}
function validate_login($loginname,$pass) {
require '../../common/createdbconn.php';
// validate user
$sql="SELECT id, fullname from m_user where login_name='$loginname' and password='$pass'";
//$sql="SELECT mu.id as id, mu.fullname as fullname, mu.office_id as office_id, xurm.role_id as role_id from m_user mu, x_user_role_mapping xurm where mu.id = xurm.user_id and mu.login_name='$loginname' and mu.password='$pass'";
$result=mysqli_query($conn,$sql);
$login_id=mysqli_fetch_row($result);
session_start();
$sessionid = session_id();
$sql_sessionid="update m_user set session_id='$sessionid' where login_name='$loginname'";
$result=mysqli_query($conn,$sql_sessionid);
$_SESSION['login_id']=$login_id[0];
$_SESSION['fullname']=$login_id[1];
$_SESSION['logged_in']=true;
$_SESSION['loginname']=$loginname;
return $login_id[0];
}
?>
login_action.php code
<?php
require_once '../../common/createdbconn.php';
require_once '../model/login_save.php';
$loginname=$_POST["user"];
$password=$_POST["pass"];
$pass=md5($password);
$login_status='';
$login_status=SignIn($loginname,$pass);
if ($login_status=='' || $login_status=='NO_USERNAME') { // Validation passed
session_start(); //starting the session for user profile page
$error ="Username or Password is invalid";
header("location:../view/login.php?session_id=".session_id());
}
else{
header("location:../../cbs/view/home.php?login_status=$login_status");
session_destroy();
}
?>
login.php code
<!DOCTYPE html>
<?php
require '../../common/createdbconn.php';
?>
<html>
<head>
<meta charset="UTF-8">
<title>CBS HELPDESK,ASSAM CIRCLE</title>
<link rel="icon" href="../../images/IP.png" type="image/png" sizes="100x56">
<link rel="stylesheet" href="../../css/style.css">
</head>
<body>
<img src="../../images/indiapost.jpg" style="width:1600px;height:120px;">
<h1>Welcome to Circle Processing Centre-Assam</h1>
<div style="color: Red;">
<p>
<?php
echo (isset($_GET['login_status']) ? htmlentities($_GET['login_status'], ENT_QUOTES) : '');
?>
</p>
</div>
<div class="wrapper">
<div class="container">
<h2>Login to Continue</h2>
<form method="post" action="../controller/login_action.php" class="form">
<input id="user" name="user" type="text" placeholder="Enter Your UserID">
<input id="pass" name="pass" type="password" placeholder="Enter Your Password">
<button id="login" name="login" type="submit">LogIn</button>
</form>
</div>
</div>
</body>
</html>
home.php
<!DOCTYPE html>
<html>
<head>
<title>CBS HELPDESK,ASSAM CIRLCE</title>
<link rel="stylesheet" href="../../css/home_style.css">
<link rel="icon" href="../../images/IP.png" type="image/png" sizes="100x56">
<script type="text/javascript">
var tmonth=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
function GetClock(){
var d=new Date();
var nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getYear();
if(nyear<1000) nyear+=1900;
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds();
if(nmin<=9) nmin="0"+nmin
if(nsec<=9) nsec="0"+nsec;
document.getElementById('clockbox').innerHTML=""+tmonth[nmonth]+" "+ndate+", "+nyear+" "+nhour+":"+nmin+":"+nsec+"";
}
window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>
</head>
<body>
<h1>Circle Processing Centre(CBS)<br>
O/O The Chief Postmaster General, Assam-781001</h1>
<header>
<marquee style="font-size:50px;" behavior="scroll" direction="left">CBS Offices as on <?php echo date("d-m-y");?> = 507</marquee>
</header>
<nav>
<ul>
<li>User Related Requests</li>
<li>List of CBS Offices in Assam</li>
<li>Migration Plans</li>
<li>ATM Sites-Assam</li>
<li>FAQs/Instrcutions/Orders</li>
<li>Contact Us</li>
<li>Logout</li></ul>
</nav>
<section>
<table>
<tr>
<th>Division</th>
<th>No of Total Offices</th>
<th>No of CBS Offices</th>
<th>Achievement in %</th>
</tr>
</table>
</section>
<footer>
<div id="clockbox">
</div>
</footer>
</body>
</html>
In home.php, you should first check if the session exists and redirect to the login page (if it's not already done).
Then you could display the ursername like this anywhere you want :
<div><?php echo $_SESSION['fullname']; ?></div>
or
<div><?= $_SESSION['fullname'] ?></div>
Hope you are saving logged in user name in $_SESSION['loginname']=$loginname;
Use session_start(); at the starting of login_save.php and <?php session_start(); ?> at the starting of home.php
User name you can call in home.php using
$name=$_SESSION['loginname'];
echo $name;
I think you are using login_name as username in your table.
You store login_name in session so simply display the username from session.
Don't forget start session on home page and always start session on the top of page.You start session in the middle of code on login_save.php
Use this code on your home page
<?php
session_start();
echo $_SESSION['login_name'];
?>

Print Username on each HTML Page

I have the following line in my HTML file for my homepage. How come it won't print out the name of the current user when they log in? I have the line in the body section of the html file. I want to put it on all my pages too but it won't display. The user does exist as it logs in succesfully via my php echo mesage.
This line:
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
Here is the login page:
<?php
function SignIn() {
require_once("constants.php"); //Now constants will be accessible
session_start();
try {
$link = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$username = $_POST['username']; //no need to esaping as we will use prepared statements
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
//You need to define a new column named "id" which will be int auto_increment and it will be your primary key
$sql = "SELECT id, username, password FROM users where username = :username AND password = :password";
//Prepare your query
$stmt = $link->prepare($sql);
//Execute your query binding variables values
$stmt->execute(array(':username'=>$username, ':password'=>$password));
//Fetch the row that match the criteria
$row = $stmt->fetch();
if (!empty($row['username']) && !empty($row['password'])) {
$_SESSION['is_logged'] = true; //Now user is considered logged in
$_SESSION['username'] = $row['username'];
$_SESSION['id'] = $row['id'];
//Never store passwords in $_SESSION
echo "Welcome to your User Account for CSIT Conference. Click to go home: ";
echo ' Home Page . ';
echo "Or here to go to your assigned papers: ";
echo ' Assigned Papers . ';
} else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
}
$link = null;
} else {
echo 'Please enter username and password.';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
Here is the home page. Eventually I want it on all the pages.
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="import" href="navigation.html">
</head>
<body>
<center> <b>World Congress CS-IT Conferences 2016</center>
<div id="horizontalmenu">
<ul>
<li>Home<br/></li>
<ul> <li>General Information <ul>
<li>About</li>
<li> Conference Fee</li>
<li>Hotel</li> </ul>
<li>Keynote Speakers<br/></li>
<li>Call for Papers<br/></li>
<li>Important Dates<br/></li>
<li>Major Areas<br/></li>
<li>Paper Submission<br/></li>
<li>Login<br/></li>
<li>Registration<br/></li>
<li>Conference Program<br/></li>
<li>Guidelines<br/></li>
<li>Comments<br/></li>
</ul>
</nav></b>
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
<br><br>
<div class="zoom pic">
<center> <img src="images/technology.png" alt="portrait"> <center>
</div>
</body>
</html>
You are starting the session inside of your SignIn() function. Remove session_start(), and instead put the following at the top of your file to start your session:
if (!session_id()) #session_start();
You must also include the above line anywhere that you want to use the session data (for example, it should be the first line in your index file.)
* All of this assumes that you either have PHP setup to execute in a .html file, or your file is actually index.php instead of index.html

PHP + mysqli trying to set up settings site for logged in user

I'm learning php and I'm using a tutorial to build a small community site.
I already have sign up, login and lost password set up as well as a profile page where the user can see his data which is saved in the database.
Now I'm trying to create a settings page where the user can edit his information and I scaled it down to just change the password for now for testing purposes.
So, to see if the user is logged in, I have this function, which I included on my settings page:
<?php
include_once("db_conx.php");
// Files that inculde this file at the very top would NOT require
// connection to database or session_start(), be careful.
// Initialize some vars
$user_ok = false;
$log_id = "";
$log_username = "";
$log_password = "";
// User Verify function
function evalLoggedUser($conx,$id,$u,$p){
$sql = "SELECT ip FROM users WHERE id='$id' AND username='$u' AND password='$p' AND activated='1' LIMIT 1";
$query = mysqli_query($conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
}
}
if(isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) {
$log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
$log_username = preg_replace('#[^a-z0-9]#i', '', $_SESSION['username']);
$log_password = preg_replace('#[^a-z0-9]#i', '', $_SESSION['password']);
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
} else if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){
$_SESSION['userid'] = preg_replace('#[^0-9]#', '', $_COOKIE['id']);
$_SESSION['username'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['user']);
$_SESSION['password'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['pass']);
$log_id = $_SESSION['userid'];
$log_username = $_SESSION['username'];
$log_password = $_SESSION['password'];
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
if($user_ok == true){
// Update their lastlogin datetime field
$sql = "UPDATE users SET lastlogin=now() WHERE id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
?>
And this is the settings page:
<?php
include 'php_includes/db_conx.php';
include 'php_includes/login_ex.php';
include_once("php_includes/check_login_status.php");
// Initialize any variables that the page might echo
$u = "";
$sex = "Male";
$userlevel = "";
$country = "";
$joindate = "";
$lastsession = "";
$password = "";
// Make sure the _GET username is set, and sanitize it
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: index.php");
exit();
}
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
// Check to see if the viewer is the account owner
$isOwner = "no";
if($u == $log_username && $user_ok == true){
$isOwner = "yes";
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$gender = $row["gender"];
$country = $row["country"];
$userlevel = $row["userlevel"];
$signup = $row["signup"];
$lastlogin = $row["lastlogin"];
$joindate = strftime("%b %d, %Y", strtotime($signup));
$lastsession = strftime("%b %d, %Y", strtotime($lastlogin));
if($gender == "f"){
$sex = "Female";
}
}
?>
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.css" rel="stylesheet" media="screen" type="text/css">
<link href="css/custom.css" rel="stylesheet" type="text/css">
<link href="css/bootstrap-min.css" rel="stylesheet" media="screen" type="text/css">
<script src="js/main.js"></script>
<title>KZ|Language exchange</title>
</head>
<body>
<div id="custom-bootstrap-menu" class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand" href="#">Brand</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-menubuilder"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-menubuilder">
<ul class="nav navbar-nav navbar-left">
<li>Home
</li>
<li>Profile
</li>
<li>About Us
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><?php
if ($isOwner == "yes") {?>
<a class="navbar-brand" href="logout.php" style="border-left: 1px solid; padding-left: 10px;">Logout</a>
<?php
}
?>
</li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="row-fluid">
<div class="col-md-9">
<h3><?php echo $u; ?></h3>
<p>Is the viewer the page owner, logged in and verified? <b><?php echo $isOwner; ?></b></p>
<p>Gender: <?php echo $sex; ?></p>
<p>Country: <?php echo $country; ?></p>
<p>User Level: <?php echo $userlevel; ?></p>
<p>Join Date: <?php echo $joindate; ?></p>
<p>Last Session: <?php echo $lastsession; ?></p>
<p>Password: <?php echo $password; ?></p>
<?php var_dump($_SESSION);
var_dump($_SESSION['username']);
?>
<?php
// i need to make sure that $isOwner = "yes"; so only logged in users see the form and can change the password
if (isset($_POST['submit'])) {
$password = $_POST["password"];
var_dump($password);
$sql = "UPDATE users SET password='$password' WHERE username='$u'";
}
?>
<h3>Create new password</h3>
<form action="user.php" method="post">
<div>Password</div>
<input type="text" class="form-control" id="password" name="password">
<br /><br />
<input type="submit" name="submit" value="Submit">
<p id="status" ></p>
</form>
</div>
<div class="col-md-3">
<div class="loginbox">
<?php
if ($isOwner == "yes") {?>
<h3>Welcome <?php echo $u; ?>!</h3>
<?php
if ($isOwner == "yes") {?>
<p>Last online: <?php echo $lastsession;?> </p>
<br /><br />
<?php
}
?>
<button class="btn btn-default" href="logout.php">Log Out</button>
<?php
}
?>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
</body>
<?php
include 'php_includes/footer.php';
?>
</html>
For some reason nothing is changing in the db when i hit submit, its so weird i am totally out of ideas...
But my knowledge is so limited that I can't see where the error lies and i am stuck.
Does anyone have an idea on how I could make this work?
Thanks in advance!
EQ
Why are you using a select query on users where you check on ID, Username and password. I assume every username has his own ID so you can just check on ID. Dont put password in the session.
change to:
<form action="" method="post">

Categories