I would like to delete a row from my users table when the user clicks a button, the user needs to be logged in do delete their own account.
I have echo'd the $user_id which shows '4', which is the correct id for the logged in user, so user_id = $user_id
This is the page that I have which holds the button which I want to delete the users row in the database
<?php
include_once 'dbconfig.php';
if(!$user->is_loggedin())
{
$user->redirect('index.php');
}
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
$stmt = $DB_con->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>Welcome - <?php print($userRow['user_email']); ?></title>
</head>
<body>
<div class="header">
<div class="right">
<label><i class="glyphicon glyphicon-log-out"></i> logout</label>
</div>
</div>
<div class="content">
Welcome <?php print($userRow['user_name']); ?> <br>
<?php print($userRow['team_name']);?><br>
Rank <?php print($userRow['user_rank']); ?> <br>
Players
Teams
<form action='teams.php' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
<?php echo $user_id?>
</div>
</body>
</html>
I think your problem is your form action(teams.php) which will receive the post data.Your delete code is on the same file and logically $_POST['leave'] will never be set in this page.
Just try to remove your teams.php in your forms action attribute.
<form action='' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
or in your teams.php file add your delete code
//Make sure you have started the session before using it
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
Another piece of advise is use parameterize query.
Example:
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = ? ");
$stmt-> bindParam(1,$user_id);
$stmt->execute();
}
<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} ?>
Delete
<?php if(isset($_GET['id'])){
$user_id = $_SESSION['user_session'];
$id=$_GET['id'];
if($id==$user_id){
$sql = "DELETE FROM Tablename WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
}?>
Related
I have problem with html and php,so I created login page and all functions for login,but I want to put username in header (Like a facebook) and have problem.Username is hidden when I add php code.
Everything work perfect,here is my HTML code.
pocetna.html
<?php
session_start();
?>
<html>
<head>
<title>
weekta RolePlay | Pocetna
</title>
<link rel="stylesheet" href="style/styless.css">
<link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">
</head>
<body>
<header>
<a class="logo" href="/" style="text-decoration: none;color: #1260a8;font-size: 30px;font-family: 'Jost', sans-serif;"><p>weekta</p></a>
<nav>
<ul class="nav__links">
<li>Services</li>
<li>Projects</li>
<li>About</li>
<li><span><?php echo( $_SESSION['korisnickoime'] );?></span></li>
</ul>
</nav>
<a class="cta" href="index.html">Login</a>
<p class="menu cta">Menu</p>
</header>
<div id="mobile__menu" class="overlay">
<a class="close">×</a>
<div class="overlay__content">
Services
Projects
About
</div>
</div>
<script type="text/javascript" src="mobile.js"></script>
</body>
</html>
And here is login_process.php
<?php
$mysql_host="localhost";
$mysql_user="root";
$mysql_password="";
$mysql_db="weekta";
$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password);
mysqli_select_db($conn, 'weekta');
session_start();
if(isset($_POST['korisnickoime'])){
$username=$_POST['korisnickoime'];
$password=$_POST['sifrajedan'];
$sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)==1){
header("Location:pocetna.html");
echo " Dobodosao $username";
exit();
}
else{
echo " Pogresna lozinka.";
exit();
}
}
?>
Can someone help me?Thanks.
You are not setting $_SESSION['username'] after your user was found in the db.
Im not a PHP expert, but you need to do something like $_SESSION['username'] = 'xyz' i think. Besides that your select query is vunerable to sql injection.
https://www.php.net/manual/en/security.database.sql-injection.php
In your script there is one mistake
$sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";
in this query near username where korisnickoime='".$username."'AND sifrajedan='".$password."' there is not space between $username and AND.
The end result of this query after appending username and password will be like
SELECT * FROM loginform where korisnickoime='user1'AND sifrajedan='xyz' limit 1";
This Query will break so please add a little space between, replace your Query string with this.
$sql="SELECT * FROM loginform where korisnickoime='".$username."' AND sifrajedan='".$password."' limit 1";
Your PHP script could be like this
index.php
<form method="post" name="login">
<label for="username">Username:</label><br>
<input type="text" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" name="password"><br>
<button type="submit" name="login">Log in</button>
</form>
<?php
session_start();
if(isset($_POST['username']) and isset($_POST['password']))
{
$username = $_POST['username'];
$pass = $_POST['password'];
$query = "SELECT * FROM `person` WHERE name='$username' and pass='$pass'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
header('Location: homepage.php');
}
else
{
$msg = "Wrong credentials";
}
}
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
Then in homepage.php
<nav>
<ul class="nav__links">
<li>Services</li>
<li>Projects</li>
<li>About</li>
<li><a href="#">
<span>
<?php
session_start();
if(!isset($_SESSION['username']))
{
die("You are not logged in!");
}
$username = $_SESSION['username'];
echo "Hai " . $username;
?>
</span></a></li>
</ul>
</nav>
PS: TO make your Query Secure use parameterized query like this
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare(SELECT * FROM loginform where korisnickoime='?' AND sifrajedan='?' limit 1");
$stmt->bind_param("ss", $username, $password);
// set parameters and execute
$username = "John";
$password = "Doe";
$result = $stmt->execute();
?>
I'm building a simple app to send confirmation emails. I have a MySQL table with 4 columns: id, user_email, user_name and user_track. The form consists of a selectbox that shows all the user_email stored and two text inputs that should be autocompleted when an email is selected.
I have tried the following, but it just echo's all the entries for user_track and user_name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data ORDER BY id DESC";
$option = '';
$artist = '';
$track = '';
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$option .= '<option value = "'.$row['user_email'].'">'.$row['user_email'].'</option>';
$track .= '<input type="text" name="track" required value = "'.$row['user_track'].'">';
$artist .= '<input type="text" name="artist" required value = "'.$row['user_name'].'">';
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Admin</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<h1>Accepted demo</h1>
<form action="demo.php" method="post">
<select name="select">
<?php echo $option; ?>
</select><br><br>
<?php echo $track; ?><br><br>
<?php echo $artist; ?><br><br>
<input type="date" name="date" placeholder="Release Date" required>
<br><br>
<input style="margin-top:10px;" class="btn" type="submit" value="Send email">
</form>
</body>
</html>
<?php
$conn->close();
?>
update From
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data ORDER BY id DESC";
To
$sql = "SELECT id, user_email, user_name, user_track FROM demo_data WHERE user_email='".$_POST['selected_user_email']."' ORDER BY id DESC";
where selected_user_email is the name of input field that is being posted
I am trying to set up a login system but the page is not doing the validation of the user and passwors. I know is connecting to the database but it doesn't show any results after the for each statement.
I have two files one for the login form(login.php) and one for the login to the database(process.php).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Login Page</title>
</head>
<body>
<div>
<form action="process.php" method="POST">
<p>
<label>Username:</label>
<input type="text" id="user" name="user">
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass">
</p>
<p>
<label>Username:</label>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php
<?php
//Get values from login.php file
$username = $_POST['user'];
$password = $_POST['pass'];
//Stop SQL injection
/* $username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);*/
//Connect to the server and select database
$domainsn = 'mysql:host=localhost;dbname=login';
$username = 'root';
$password = 'costarica';
try {
$db = new PDO ($domainsn, $username, $password);
echo "Connected";
} catch (Exception $e) {
$error_message = $e->getMessage();
echo "Coudn't connect due to $error_message";
}
$query = "SELECT * FROM users WHERE username = '$username' AND password ='$password'";
$result = $db->query($query);
//echo "$result";
foreach ($result as $results) {
echo "$results";
echo $users['id'];
if ($results['username'] == $username && $results['password'] == $password) {
echo "Login success!!! Welcome ".$results['username'];
} else {
echo "failed try {} catch ( $e) {}";
}
}
?>`enter code here`
You can use this i hope it will help.
$query = "SELECT * FROM users WHERE username = '".$username."' AND password ='".$password."' ";
$result = $db->query($query);
if($result->num_rows>0){
// User exists
}else{
// User not exists.
}
For the past couple days, I have been trying to learn how to search an mysql database. So far I have the code below. for some reason it isn't searching and giving me results back. my database is named score and the table is all scores. Someone please help me with this.
It should be searching my database but it's coming up with no results. I have made sure everything is correct.
This file is searching.php
<?php
if (isset($_POST['search'])) {
$id = $_POST['id'];
$connect = mysqli_connect("localhost", "root", "root", "score");
$query = "SELECT `name` FROM `all_scores` WHERE `id` = $id LIMIT 1";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$name = $row['name'];
}
} else {
echo "Undifined ID";
$gameid = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$gameid = "";
}
this is search.php
<!DOCTYPE html>
<html>
<head>
<title> PHP FIND DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
</body>
</html>
To get the form values inside the php file you need to use $_POST. Here's an example using PDO. You're only retrieving one row so you don't need the while loop.
searching.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $conn->prepare("SELECT `name` FROM `all_scores` WHERE `id` = :id LIMIT 1");
$q->bindValue(':id', $_POST['id'], PDO::PARAM_STR, 50);
$q->execute();
if ($q->rowCount() > 0) {
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
Html:
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
Take some time look at several other examples
I am trying to delete a row from a table using PHP (PDO) on a page listing the rows entered into the database. I've been tinkering with the delete.php code to try to make it work but to no avail. I appreciate any help.
Below is my code:
listview.php
session_start();
include_once('../includes/connection.php');
include_once('../includes/events.php');
$event = new Event;
$events =$event->fetch_all();
if(isset($_SESSION['logged_in'])) {
//display index
?>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to the admin page</title>
</head>
<body>
<div class="container">
<h1>The List of Events</h1>
<ol>
<?php foreach ($events as $event) { ?>
<li>
<?php echo $event['event_name']; ?>
<?php echo $event['event_date']; ?>
<?php echo $event['event_location']; ?>
<?php echo $event['description']; ?>
<?php echo $event['start_time']; ?>
<?php echo $event['end_time']; ?>
<?php echo $event['poc_name']; ?>
<?php echo $event['poc_email']; ?>
<?php echo $event['poc_number']; ?>
<!--edit/delete links-->
Edit
Delete
<!--end edit/delete links-->
</li>
<?php } ?>
</ol>
</div>
</body>
</html>
<?php
} else {
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//check the fields in the login form
if(empty($username) or empty($password)) {
$error = 'All fields are required';
} else {
$query = $dbh->prepare("SELECT * FROM admin WHERE username = ? AND userpassword = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if($num == 1) {
//correct
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//incorrect
$error = 'Incorect details';
}
}
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Squeegee Admin Login</title>
</head>
<body>
<div class="container">
Squeegee Admin
<br/>
<?php if (isset($error)) { ?>
<small style="color:#aa000; "><?php echo $error; ?> </small>
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
</html>
<?php } ?>
Connection
<?php
// mysql hostname
$hostname = 'localhost';
// mysql username
$username = 'root';
// mysql password
$password = '';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=squeegee", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
events.php
<?php
class Event {
//queries from database
public function fetch_all() {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events");
$query->execute();
return $query->fetchAll();
}
//queries specific article via id
public function fetch_data($event_id) {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events WHERE event_id = ? ");
$query->bindValue(1, $event_id);
$query->execute();
return $query->fetch();
}
}
?>
delete.php
<?php
include('../includes/connection.php');
$event_id=$_GET['event_id'];
$result = $dbh->prepare("DELETE FROM events WHERE event_id= :event_id");
$result->bindParam(':event_id', $event_id);
$result->execute();
header("location: index.php");
?>
As your question stands, it seems you're accessing the wrong index.
In your link it is defined as id:
Delete
// ^
But then accessed in your PHP file as:
$event_id=$_GET['event_id'];
Must be: $event_id = $_GET['id'];
Either you change your url as ?event_id in the anchor or change the array index in your PHP $event_id = $_GET['id'];. The important things is they must match.