Row won't update in database - php

I'm making a community site thing.
I'm currently making the option to change your password.
But, when I try to use it, it won't work..
Why is this? How do I fix it?
My code:
Settings.php (Where I change the pass)
PHP:
<?php
error_reporting(E_ALL);
include_once('includes/connection.php');
include_once('includes/user.php');
if(isset($_SESSION['logged_in'])){
if(isset($_POST['oldpass']) and isset($_POST['newpass'])){
$name = $_COOKIE['name'];
$oldpass = md5($_POST['oldpass']);
$newpass = md5($_POST['newpass']);
$query = $pdo->prepare("SELECT * FROM users WHERE username=? AND password=?");
$query->bindValue(1, $name);
$query->bindValue(2, $oldpass);
$query->execute();
$num = $query->rowCount();
if($num==1){
$query = $pdo->prepare("UPDATE users SET password=? WHERE username=?");
$query->bindValue(1, $newpass);
$query->bindValue(2, $name);
$result = $query->execute();
if($result==1){
header('Location: logout.php');
}else{
echo "Something went wrong.";
}
}
}
}
?>
HTML:
<html>
<head>
<title>MackNet</title>
<link rel="stylesheet" type="text/css" href="assets/style.css">
</head>
<body>
<div id="main">
<?php
$name = $_COOKIE['name'];
$pass = $_COOKIE['pass'];
$user = new User();
$row = $user->fetch_all($name, $pass);
?>
<div id="toolbar">
<?php
echo " <a href='main.php'>Home</a> ";
echo " <a href='logout.php'>Logout</a> ";
echo " <a href='settings.php'>Settings</a> ";
if($row['group'] == 2){
echo " <a href='users.php'>Manage Users</a> ";
}
?>
<hr>
</div>
<form action="settings.php" method="POST">
<input type="password" name="oldpass" placeholder="Old Password">
<input type="password" name="newpass" placeholder="New Password">
<input type="submit" value="Change password">
</form>
</div>
</body>
</html>
If you need any more code, tell me.
Thanks // Mackan90095

What error do you get? Or does it never get inside the if($num==1)?
Maybe its smart to retrieve the users id and use that to change the password. Imagine two users having the same username, that would change both their passwords.
I would also include a password confirmation field to make sure they enter the new password twice (just as a precaution).
Useful site: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Why dont you try using try catch to see the error and replace if($result==1) with if($result)
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$query = $pdo->prepare("SELECT * FROM users WHERE username=? AND password=?");
$query->bindValue(1, $name);
$query->bindValue(2, $oldpass);
$query->execute();
$num = $query->rowCount();
if($num==1){
$query = $pdo->prepare("UPDATE users SET password=? WHERE username=?");
$query->bindValue(1, $newpass);
$query->bindValue(2, $name);
$result = $query->execute();
if($result)
header('Location: logout.php');
}
}
catch (PDOException $e) {
echo "DataBase Error: ".$e->getMessage();
}
catch (Exception $e) {
echo "General Error: ".$e->getMessage();
}

You have a beautiful code, but I've seen only this:
change
<form action="settings.php" method="POST">
to
<form action="Settings.php" method="POST">
Settings.php is capitalized?

Related

How to change this part of code as PHP prepared statement?

Statement
In login_check.php, it worked but I would like to change it into the prepared statement.
login.php
<body>
<div class="container">
<h1>Please Log In to the System</h1>
<form method="post" action="login_check.php">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" autocomplete="off" required>
<button type="submit" name="login" value="Log In">Log In</button>
</form>
</div>
</body>
login_check.php
<body>
<?php
//Establish connection
include 'connection.php';
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
$sql = "SELECT * FROM admins WHERE admin_username = '".mysqli_real_escape_string($conn, $_POST['username'])."' and admin_password = '".mysqli_real_escape_string($conn, $_POST['password'])."'";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_array($query);
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if(!$result) //Username or Password is invalid!
{
?>
<div class="container">
<h1>Username or Password is invalid!</h1>
<form method="post" action="login.php">
<button type="submit">Back</button>
</form>
</div>
<?php
}
else //Username and Password are valid!
{
$_SESSION["admin_id"] = $result["admin_id"];
$_SESSION["admin_username"] = $result["admin_username"];
session_write_close();
header("location:front.php");
}
$conn->close();
?>
</body>
To change to prepared statements, you just need to
replace variables in your query with a ?
prepare the query
bind variables to the parameters
execute the statement
For your code that would look like this:
$sql = "SELECT * FROM admins WHERE admin_username = ? and admin_password = ?";
$stmt = $conn->prepare($sql) or die($conn->error);
$stmt->bind_value("ss", $_POST['username'], $_POST['password']);
$stmt->execute() or die($stmt->error);
$result = $stmt->get_result();
Note that you should not be storing passwords in plain text in your database. Please look into PHPs password_hash and password_verify functions to properly handle your passwords. You would use password_hash when storing the password in the database, and then your code for verifying the user would look something like:
$sql = "SELECT * FROM admins WHERE admin_username = ?";
$stmt = $conn->prepare($sql) or die($conn->error);
$stmt->bind_value("s", $_POST['username']);
$stmt->execute() or die($stmt->error);
$result = $stmt->get_result() or die($stmt->error);
$row = $result->fetch_array();
if (!$row|| !password_verify($_POST['password'], $row['admin_password']) {
// invalid username or password
login_check.php
<?php
//Establish connection
include 'connection.php';
$sql = "SELECT * FROM admins WHERE admin_username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array())
{
$hash = password_hash($_POST['password'],PASSWORD_DEFAULT);
mysqli_query($conn,"UPDATE admins SET admin_password = '$hash' WHERE admin_id='{$row['admin_id']}");
}
if(!$row || !password_verify($_POST['password'],$row['admin_password']))
{
?>
<div class="container">
<h1>Username or Password is invalid!</h1>
<form method="post" action="login.php">
<button style="font-size: 30px" type="submit" class="btn btn-dark"><b>Back</b> <i class="fas fa-arrow-alt-circle-left"></i></button>
</form>
</div>
<?php
}
else
{
$_SESSION["admin_id"] = $result["admin_id"];
$_SESSION["admin_username"] = $result["admin_username"];
session_write_close();
header("location:front.php");
}
$stmt->close();
$conn->close();
?>
</body>
There is no syntax error shown up but I think there are some mistakes in
=> mysqli_query($conn,"UPDATE admins SET admin_password = '$hash' WHERE admin_id ='{$row['admin_id']}");
=> if(!$row || !password_verify($_POST['password'],$row['admin_password']))
Form this code, the result is it always returns as username or password is invalid, even I put the valid ID and Password.

Notice: Trying to get property 'num_rows' of non-object

I'm reworking a login form to PDO based with OOP in mind. And I am running into the error given above. So I have two files one is an login.php and one is an included file called functions.inc.php
The code for the login.php is as follows.
<?php
include_once("includes/functions.inc.php");
// get username and password from $_POST
if(!empty($_POST)){
$username = $_POST['email'];
$password = $_POST['password'];
// check if a user can login (function)
if(canilogin($username, $password)){
session_start();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
header('Location: index.php');
}
else{
$error = true;
// if no -> $error tonen
}
}
?><!DOCTYPE html>
<html lang="en">
<body class="login">
<div class="grid container_login">
<div class="login_grid">
<form class="form_login" action="" method="post">
<?php if( isset($error) ): ?>
<div class="form__error">
<p>
Sorry, we can't log you in with that email address and password. Can you try again?
</p>
</div>
<?php endif;?>
<div>
<label for="email">EMAIL</label><br/>
<input type="text" id="email" name="email" placeholder="Lucasdebelder#snapshot.be" required>
</div>
<div>
<label for="password">PASSWORD</label><br/>
<input type="password" id="password" name="password" placeholder="Atleast 8 characters" required>
</div>
<div>
<input type="submit" value="LOG IN" class="btn_login">
</div>
<p class="center_align">Or</p>
<br/>
<a class="center_align" href="register.php">Register here.</a>
</form>
</div>
</body>
</html>
And the functions.inc.php where the error is happening, to be precise it happens at if($result->num_rows != 1){.
Also the first few lines were the once that worked before but that is done with real escape string to secure against SQL inject but it's kinda a wacky way to do and I decided to try to rework it to PDO.
<?php
function canilogin( $username, $password){
/* THIS IS THE OLD WAY THAT WORKED/WORKS
$conn = new mysqli("localhost", "root", "root", "snapshot");
$query = "select * FROM users WHERE email='".$conn->real_escape_string($username). "'";
$result = $conn->query($query);
*/
$conn = new PDO('mysql:host=localhost; dbname=snapshot', 'root', 'root');
//$query = "select * FROM users WHERE email='".$conn->real_escape_string($username). "'";
$statement = $conn->prepare("select * from users where email = :username");
$statement->bindValue(':username', $username);
$statement->execute();
$result = $statement->execute();
if($result->num_rows != 1){
return false;
}
$user = $result->fetch_assoc();
if(password_verify($password, $user['password'])){
return true;
}
else{
return false;
}
}
?>
The reason you are having the issue is that $result is not correct. Once $statement->execute(); is executed it becomes a PDOStatement object.
First of all remove $result = $statement->execute(); and try
if($statement->rowCount() != 1){
return false;
}
$user = $statement->fetch();
if(password_verify($password, $user['password'])){
return true;
}
else{
return false;
}

PHP Prepared statements - Failing to retrieve the string from the database

I'm still fairly new to the prepared statements because it was brought to my attention by another user. I've been able to create a registration function that properly prepares the statement, binds it and then executes it. It goes into the database just fine. However, I'm not sure I understand how the login part would work. I'm trying to fetch a row and the result I keep getting is "1" but not the row + data inside the row. Any advice?
Database:
login.php (where the form is located)
<form id="loginform" class="form-horizontal" role="form" action="" method="post">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="Lusername" placeholder="Username or Email">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="Lpassword" placeholder="Password">
</div>
<div class="input-group">
<div class="checkbox">
<label>
<input id="login-remember" type="checkbox" name="remember" value="1"> Remember me
</label>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button id="btn-login" type="submit" class="btn btn-success"><i class="icon-hand-right"></i>Submit</button>
</div>
</div>
</form>
script:
<script type="text/javascript">
$(function() {
$("#loginform").bind('submit',function() {
var username = $('#login-username').val();
var password = $('#login-password').val();
$.post('scripts/loginFunction.php',{username:username, password:password}, function(data){
$('#signupsuccess').show();
}).fail(function(){{
$('#signupalert').show();
}});
return false;
});
});
</script>
loginFunction.php
<?php
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT `Username`, `Password` FROM `users` WHERE `Username` = ?");
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
/*if($stmt->num_rows == 1){
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row);
// here is where you could verify the password
if(password_verify($password, $row['Password'])) {
// good password
echo 'all good!';
}
} else {
//echo "failed to find row";
}*/
?>
loginFunction.php that does work and queries the database properly
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($query);
if($result->num_rows == 1){
$row = mysqli_fetch_array($result);
if(password_verify($password, $row['Password'])){
echo "Login successful!";
}
else{
echo "Login failed.";
}
}
EDIT: Here is the code you should use. Note how $stmt is carried throughout:
$stmt = $conn->prepare("SELECT `Username`, `Password` FROM `users` WHERE `Username` = ?");
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
/*if($stmt->num_rows == 1){
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row);
// here is where you could verify the password
if(password_verify($password, $row['Password'])) {
// good password
echo 'all good!';
}
} else {
//echo "failed to find row";
}*/
I have resolved the issue. When I went to fetch, I needed to store it in a separate variable than the one that the user is storing their entered password into. This can be reflected in the code below:
<?php
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
$dbusername = ""; //These two being the new variables
$dbpassword = "";
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT Username, Password FROM users WHERE Username = ?;");
$stmt->bind_param('s', $username);
$stmt->execute();
if($stmt->execute() == true){
$stmt->bind_result($dbusername, $dbpassword);
$stmt->fetch();
if(password_verify($password, $dbpassword)) {
echo 'successful';
}
else{
echo 'failed';
}
}
else{
echo 'failed';
}
?>

php using pdo simple login system issues

<?php
if(isset($_POST["submit"])){
require 'Config.php';
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$Name = $_POST['Name'];
$Password = $_POST['Password'];
$message ="";
$stmt = $conn->prepare("SELECT COUNT(*) FROM user WHERE Name='$Name' and Password='$Password'");
$stmt->execute();
$result = $stmt->fetchcolumn();
if($result > 0)
{
$_SESSION['Logged In'] = $Name;
$_SESSION['Logged In'] = $Password;
if(isset($_SESSION['Logged In']))
{
echo $result;
session_start();
header('Location: Main.php');
exit();
}
}
elseif($result == 0)
{
echo $result;
echo "Invalid Username or Password";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$conn = null;
}
?>
i need help with this simple login system if i comment out the header redirect the echo result shows i am only getting 1 result as expected when i put the redirect in the page just refreshes instead of going to the next page.
There are a few simple issues in this code
First you must start the session before you do anything with it. In fact its best to start it at the top of every script before doing anything else.
Also because you have echoed something to the browser before you have run the header, this will be a probelm. Headers have to be sent before any page data.
Also your code is liable to SQL Injection so use prepared and parameterised queries to avoid this.
You also appear to be storing a plain text password in the database. another big No No
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords
If you are using a PHP version prior to 5.5 there is a compatibility pack available here
<?php
session_start();
if(isset($_POST["submit"])){
require 'Config.php';
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$stmt = $conn->prepare("SELECT Password
FROM user
WHERE Name=:name");
$params = array(':name'=>$_POST['Name'])
$stmt->execute($params);
$hashedPassword = $stmt->fetchcolumn();
if(password_verify($_POST['Password'], $hashedPassword) ) {
$_SESSION['Logged In'] = $_POST['Name'];
// bad idea putting password in a session
//$_SESSION['Logged In'] = $Password;
// you just set this data so the if is unnecessary
//if(isset($_SESSION['Logged In'])) {
// cannot echo anything before doing a header()
// any way if the header works you wont see this data
// anyway as a new page will be being loaded
//echo $result;
header('Location: Main.php');
exit;
} else {
echo $result;
echo "Invalid Username or Password";
}
catch(PDOException $e) {
echo $e->getMessage();
}
$conn = null;
}
?>
As this now uses a hashed password, you will have to recreate your users and when tou do, use
$passwordToPutOnDatabase = password_hash($thepassword);
There are may issues with your code, you are storing passwords in plain text which is completely wrong, you should use password_hash() and password_verify()
I have made you a simple login/register script which will show you how to use the password_hash and password_verify()
simple_register.php
<?php
require 'db_config.php';
if(isset($_POST['register'])){
//validate email and password I'm not gonna do that for you
$password = $_POST['upass']; // when u done with validation
$email = $_POST['username'];
$hash = password_hash($password,PASSWORD_DEFAULT); //hash password
try {
$stmt = $conn->prepare("INSERT INTO users (username,password) VALUES ( ?,?)");
if($stmt->execute(array($email,$hash))){
echo "user registered";
}else{
echo "could not register"; // something wrong with your query check error log
}
} catch (Exception $e) {
error_log($e->getMessage());
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple PDO Registration</title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><input type="email" name="username" placeholder="Enter your email"></p>
<p><input type="password" name="upass" placeholder="Enter password"></p>
<button type="submit" name="register">Register</button>
</form>
</body>
</html>
login.php
<?php
ob_start();
session_start();
require 'db_config.php';
if (isset($_SESSION['loggedin'])) {
header("location:users/dashboard.php");
} else {
$loginMessage = "";
$msg_class = "";
if (isset($_POST['login'])) {
if (empty($_POST['email']) || empty($_POST['upass'])) {
$loginMessage = "Enter username and password";
$msg_class = "error";
} else {
$username = $_POST['email'];
$password = $_POST['upass'];
try {
$stmt = $conn->prepare("SELECT userID,username,password FROM users where username = ? ");
$stmt->execute([$username]);
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
foreach ($results as $row):
if (password_verify($password, $row['UserPassword'])) {
$_SESSION['loggedin'] = $row['userID'];
$loginMessage = "Login Successfully! Redirecting...";
$msg_class = "success";
header("refresh:5; url=dashboard");
} else {
$loginMessage = "Password and username does not match";
$msg_class = "error";
}
endforeach;
} else {
$loginMessage = "Invalid username";
}
}
catch (PDOException $e) {
error_log($e);
}
}
}
}
?>
</head>
<body>
<div id="main">
<h1>User Login</h1>
<div class="row">
<div class="large-6 columns large-centered" id="box">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<label>Email</label>
<input type="text" name="email" class="input" >
<label>Password </label>
<input type="password" name="upass" class="input" id="password"/><br/>
<div class="large-6 columns pull-2">Forgot Password</div>
<button type="submit" class="button" name="login" disabled="true" id="long">Login</button>
<div class="<?php echo $msg_class;?>">
<?php
echo $loginMessage;
?>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#password').keyup(function(e){
$('#long').prop('disabled', false);
});
});
</script>
</div>
db_config.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "samedicalspecialists";
try {
$conn= new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
error_log($e);
}
?>

Delete Button to Delete a User Record PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The below code is all on one file named 'useraccount.php' on my website. As it currently exists, this page has a form for the logged in administrator to add a new user account, as well as a table below that displays existing accounts already in the database. I am wanting to add a 'delete' button for each existing account, and have tried various ways of incorporating this, but have yet to find a solution that works. If anyone can share some expertise with me I would greatly appreciate it. I need to know how to setup the button to carry over the database row number variable so that the php can recognize which row to delete, as well as where and how to safely execute the delete query in the php. Notes are within the code that show my partial attempt.
Current PHP Code
<?php
require("connect.php");
if(empty($_SESSION['user']) || empty($_SESSION['adminaccess']))
{
header("Location: login.php");
die("Redirecting to login.php");
}
//BEGIN DATA FETCHING TO DISPLAY CURRENT USERS
$query = "
SELECT
id,
username,
display_name,
email,
admin
FROM users
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
//END DATA FETCHING TO DISPLAY CURRENT USERS
//BEGIN USER DELETE FUNCTION
//IM NOT SURE HOW TO SET THIS UP, OR IF IT'S EVEN IN THE RIGHT PLACE
$id = isset($_POST['id'])?intval($_POST['id']):0;
if($id>0) { $query = "DELETE FROM users WHERE id = '$id'";
}
//END USER DELETE FUNCTION
//BEGIN FOR ADD NEW USER
if(!empty($_POST))
{
if(empty($_POST['username']))
{
header("Location: useraccounts.php");
die("Redirecting to: useraccounts.php");
$error = "Please enter a username.";
}
if(empty($_POST['password']))
{
header("Location: useraccounts.php");
die("Redirecting to: useraccounts.php");
$error = "Please enter a password.";
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
header("Location: useraccounts.php");
die("Redirecting to: useraccounts.php");
$error = "Invalid E-Mail Address";
}
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
header("Location: useraccounts.php");
die("Redirecting to: useraccounts.php");
$error = "This username is already in use";
}
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
header("Location: useraccounts.php");
die("Redirecting to: useraccounts.php");
$error = "This email address is already registered";
}
$query = "
INSERT INTO users (
username,
display_name,
password,
salt,
email,
admin
) VALUES (
:username,
:display_name,
:password,
:salt,
:email,
:admin
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':display_name' => $_POST['display_name'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email'],
':admin' => $_POST['admin']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
header("Location: useraccounts.php");
die("Redirecting to useraccounts.php");
}
?>
Table that Displays 'Add New Account' Form
<h3>Add an Account</h3>
<form action="useraccounts.php" method="post">
<p class="label">Username:</p>
<input class="text" type="text" name="username" value="" />
<p class="label">Display Name(s):</p>
<input class="text" type="text" name="display_name" value="" />
<p class="label">E-Mail:</p>
<input class="text" type="text" name="email" value="" />
<p class="label">Password:</p>
<input class="text" type="password" name="password" value="" />
<p class="label">Admin Account?</p>
<input type="radio" id="r1" name="admin" value="0" checked="checked" /><label for="r1"><span></span>No</label>
<input type="radio" id="r2" name="admin" value="1" /><label for="r2"><span></span>Yes</label></br>
<p class="error"><?php echo $error; ?></p>
<button class="contact" type="submit" name="submit">Create Account</button>
</form>
Table that Displays Existing User Account
<h3>Current Accounts List</h3>
<table class="parent-accounts">
<tr>
<th><h4>ID</h4></th>
<th><h4>Username</h4></th>
<th><h4>Display Name(s)</h4></th>
<th><h4>E-Mail Address</h4></th>
<th><h4>Admin</h4></th>
</tr>
<?php foreach($rows as $row): ?>
<form action="useraccounts.php?id=<?php echo $id['id'];?>" method="post">
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlentities($row['display_name'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlentities($row['admin'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><input type="submit" name="submit" value="Delete User" /></td>
</tr>
</form>
<?php endforeach; ?>
</table>
'id' is posted by the form, and your Delete User Query seems fine. You need to execute the query. And maybe make sure you handle the deleting request before you fetching current users.
<?php
require("connect.php");
if(empty($_SESSION['user']) || empty($_SESSION['adminaccess']))
{
header("Location: login.php");
die("Redirecting to login.php");
}
//BEGIN USER DELETE FUNCTION
//IM NOT SURE HOW TO SET THIS UP, OR IF IT'S EVEN IN THE RIGHT PLACE
if(isset($_SESSION['adminaccess'])) //if user has admin privilege
{
$id = isset($_POST['id'])?intval($_POST['id']):0;
if($id>0) //if valid id for deleting is posted
{
$query = 'DELETE FROM users WHERE id = '.$id;
echo '<script>alert("Query: '.$query.'");</script>'; //debug line, remove this later
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
}
else
{
echo '<script>alert("Invalid ID: '.$id.'");</script>'; //debug line, remove this later
}
}
else
{
echo '<script>alert("No admin access privilege.");</script>'; //debug line, remove this later
}
//END USER DELETE FUNCTION
//BEGIN DATA FETCHING TO DISPLAY CURRENT USERS
$query = "
SELECT
id,
username,
display_name,
email,
admin
FROM users
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
//END DATA FETCHING TO DISPLAY CURRENT USERS
..........
?>

Categories