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.
Related
i had some problems with this code, seen some guides and arrived to this. I just started php few days ago. How exactly do you do a search of database, then compare the user input to the database username and password?
the $sqlQuery i left it empty for the sql search and maybe someone can explain what you call the "->" symbol in the loop?
I allready managed to understand and do a sign up but the tutorials never explain exactly what is going and just type.
Thanks.
<?php
include 'db.php';
include 'info.php';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sqlQuery = '';
$result = mysqli_query($connection,$sqlQuery);
if($result->num_rows > 0){
session_start();
echo 'welcome';
}else{
echo 'failed';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
</head>
<body>
<form action="login.php">
Username: <input type="text" name="username">
Username: <input type="password" name="password">
<input type = "submit" value = " Submit "/><br />
</form>
</body>
</html>
PHP PDO login with session - It's secure
index.php,general message.php, logout.php, site life.php (this page for session and put it in the other pages by required)
Database:
connection.php
<?php
$dsn = "mysql:host=localhost;dbname=mg";
$username = "root";
$password = "";
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try{
$conn = new PDO($dsn,$username,$password,$options);
} catch (PDOException $e){
echo "Error!".$e->getMessage();
}
?>
index.php:
<?php
session_start();
if(isset($_SESSION['user'])){
header("location: general message.php");
}
require "connection.php";
if(isset($_POST['login'])){
$user = $_POST['username'];
$pass = md5($_POST['password']);
$messeg = "";
if(empty($user) || empty($pass)) {
$messeg = "Username/Password con't be empty";
} else {
$sql = "SELECT username, password FROM users WHERE username=? AND
password=? ";
$query = $conn->prepare($sql);
$query->execute(array($user,$pass));
if($query->rowCount() >= 1) {
$_SESSION['user'] = $user;
$_SESSION['time_start_login'] = time();
header("location: general message.php");
} else {
$messeg = "Username/Password is wrong";
}
}
}
?>
Site life.php (and I will put it in the the other pages by require "site life.php")
//The lives of session is one hour 60*60=3600
<?php
session_start();
if(isset($_SESSION['user'])){
if((time() - $_SESSION['time_start_login']) > 3600){
header("location: logout.php");
} else {
$_SESSION['time_start_login'] = time();
}
} else {
header("location: logout.php");
}
?>
logout.php
<?php
session_start();
session_destroy();
header("location: index.php");
?>
General message.php I put this in the header (to make a refresh every hour):
// 60*60=3600 one hour
<meta http-equiv="Refresh" content="3600" >
<?php
require ('site life.php');
?>
The -> is an object operator. so you can access attribute num_rows from $result.
This is the naive example (vulnerable to SQL injection) to give you an idea, it works.
<?php
include 'db.php';
include 'info.php';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sqlQuery = "SELECT * FROM user WHERE username = '$username' and password = '$password'";
$result = mysqli_query($connection,$sqlQuery);
if($result->num_rows > 0){
session_start();
echo 'welcome';
}else{
echo 'failed';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
</head>
<body>
<form action="login.php">
Username: <input type="text" name="username">
Username: <input type="password" name="password">
<input type = "submit" value = " Submit "/><br />
</form>
</body>
</html>
I am currently trying to convert a php login I have that uses mysql (I know this is a bit dated) to using sqlsrv. This is just a learning task as I wanted to learn to migrate a site from mySQL to MSSQL.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$serverName = "localhost";
$connectionInfo = array( "Database"=>"dbname", "UID"=>"sa", "PWD"=>"123");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return $str;
}
//Sanitize the POST values
$login = clean($_POST['username']);
$password = clean($_POST['password']);
//Input Validations
if($login == '') {
$errmsg_arr[] = 'Login ID missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
}
//Create query
$qry="SELECT * FROM users WHERE Username='$login' AND Password='".md5($_POST['password'])."'";
$stmt = sqlsrv_query( $conn, $qry );
//Check whether the query was successful or not
if($stmt) {
$row_count = sqlsrv_num_rows( $stmt );
if($row_count == 1) {
//Login Successful
session_regenerate_id();
$member = sqlsrv_fetch_assoc($stmt);
$_SESSION['SESS_MEMBER_ID'] = $member['idUsers'];
$_SESSION['SESS_FIRST_NAME'] = $member['FirstName'];
$_SESSION['SESS_LAST_NAME'] = $member['LastName'];
session_write_close();
header("location: home.php");
exit();
}else {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['FirstName'];
$row_count = sqlsrv_num_rows( $stmt );
echo $row_count;
echo $stmt;
}
//Login failed
//header("location: index.php");
exit();
}
}else {
die("Query failed");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Asset Manager</title>
<link rel="stylesheet" href="assets/main.css">
<link rel="stylesheet" href="assets/login.css">
</head>
<header>
<img src="img/logo.png">
</header>
<ul>
</ul>
<div class="main-content">
<form class="form-login" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-log-in-with-email">
<div class="form-white-background">
<div class="form-title-row">
<h1>Log in</h1>
</div>
<div class="form-row">
<label>
<span>Username</span>
<input type="text" name="username" id="username">
</label>
</div>
<div class="form-row">
<label>
<span>Password</span>
<input type="password" name="password" id="password">
</label>
</div>
<div class="form-row">
<button type="submit" name="Submit" value="Login">Log in</button>
</div>
</div>
</div>
</form>
</div>
</body>
</html>
The issue is it just keeps going to the last else. I have been doing some troubleshooting as you can see in the code. the issue I think is that the rowcount does not work. When I echo ut the row count I just get a Resource 5 showing.
Any ideas?
The fix is to change
if($stmt) {
$row_count = sqlsrv_num_rows( $stmt );
if($row_count == 1) {
to:
if($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if($rows === true) {
If project is old and messy, you might consider to write wrapping functions, something like this:
function mysql_num_rows($result){
$rows = sqlsrv_num_rows($result);
// change $rows in the way you need
return $rows;
}
Update
If you have no mysql extension, mysql_num_rows() will not be available and there will be no problem to define this function.
If you can not remove mysql extension, make it my_mysql_num_rows() and replace "mysql_" with "my_mysql_".
I'm newbie to PHP, currently i'm doing first project to build a website which use to evaluate employee. The requirements are using PDO to prevent SQL injection and session.
The login.php work, but when it switch to cpanel page ( which include session.php ) it doesn't show anything. Seem like i messed up the code with PDO and mysql command too.
I use php -f session.php in terminal and have this line :
PHP Notice: Undefined index: login_user in /var/www/docs/cent285
/project1/source/session.php on line 7
PHP Fatal error: Call to a member function fetch() on a non-object
in /var/www/docs/cent285/project1/source/session.php on line 10
Loginform.php
<form action="source/login.php" method="post">
<input id="name" name="username" placeholder="username" type="text">
<input id="password" name="password" placeholder="password" type="password">
<input name="submit" type="submit" value=" Login ">
</form>
login.php
<?php
require_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = "Username or Password is invalid";
}
else
{
$pdo = connect();
$username = $_POST['username'];
$password = $_POST['password'];
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "select id, division, department from " .
"check_user(:usr,:pass) as (id integer, " .
"division text, department text)";
$statement = $pdo->prepare($sql);
$myarray = array();
$myarray[':usr'] = $username;
$myarray[':pass'] = $password;
$statement->execute($myarray);
$row = $statement->fetch(PDO::FETCH_ASSOC);
if ($row['id'] > 0) {
session_start();
$_SESSION['login_user']=$username;
$div = $row['division'];
$dept = $row['department'];
$loggedIn = TRUE;
header("Location: ../cpanel.php");
exit(); }
else
{
mysql_close($pdo);
header("location:../404.html");
}
}
}
?>
session.php
<?php
session_start();
$connection= "pgsql:host=localhost dbname=proj1_db " .
"user=bob password=somepass";
$user_check= $_SESSION['login_user'];
$ses_sql="select username from users where username='$user_check'";
$row = $ses_sql->fetch(PDO::FETCH_ASSOC);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection);
header('Location: ../index.html');
}
?>
cpanel.php
<?php
include('source/session.php');
$pdo = connect();
if (!$pdo) {
die("Could not connect");
}
$div = $_GET["div"];
$dept = $_GET["dept"];
var_dump($div);
var_dump($dept);
$myarray = array();
if ($div !== $dept) {
$sql = "select * from users_evaluations_view " .
"where department=:dept";
$myarray[':dept'] = $dept;
}
$statement = $pdo->prepare($sql);
$statement->execute($myarray);
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<?php
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
echo $row['uid'] . "<br />\n"; }
?>
<b id="logout">Log Out</b>
</div>
</body>
</html>
config.php
<?php
function connect(){
$pdoString= "pgsql:host=localhost dbname=proj1_db " .
"user=bob password=somepass";
$pdo = new PDO($pdoString);
return $pdo;
}
?>
Im creating a small basic MVC style website and currently working with my login page. I have three different folders, Model, View and Controller.
So far this is the code i have:
View: Basically just holds the login form and access the controller
<?php
session_start();
require_once('../Controller/loginController.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Energy Checker: Login</title>
</head>
<body>
<div class="formLogin">
<h2>Login to your account</h2>
<form id="loginfrm" method="post">
<label>Username: </label>
<input type="text" name ="txtUsername"placeholder="Username" required/>
<label>Password: </label>
<input type="password" name ="txtPassword" placeholder="Password"required/>
<?php
if(isset($error))
{
?>
<div class="alert alert-danger">
</i><?php echo $error; ?> !
</div>
<?php
}
?>
<input type="submit" name="btn-login" value="Login">
</form>
</div>
</body>
</html>
Controller: Just checks if the data has been posted
<?php
require_once('config.php');
require_once('../Model/loginModel.php');
$user = new Login();
if(isset($_POST['btn-login']))
{
$uname = strip_tags($_POST['txtUsername']);
$upass = strip_tags($_POST['txtPassword']);
if($user->getLogin($uname,$upass))
{
$user->redirect('../View/calculator.php');
}
else
{
$error = "Wrong Details !";
}
}
?>
Model: Carries out the select statement
<?php
class Login
{
private $dbconn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->dbconn = $db;
}
public function getLogin($uname,$upass)
{
try
{
$stmt = $this->dbconn->prepare("SELECT * FROM users WHERE Username=:uname");
$stmt->execute(array(':uname'=>$uname));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['Password']))
{
$_SESSION['user_session'] = $userRow['Username'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>
I dont receive any errors (anymore)
However when i enter users details it always says "wrong details!"
Not really sure why im getting this
Any help will be appreciated.
The txtUsername has an extra space in the HTML, maybe that is an issue with Undefined index
And for $db you don't have a property called db in the Login class
I have created a homepage where user has to login if user hasn't login.
Here is my index.php :
<?php
error_reporting(-1);
session_start();
echo $_SESSION['PHPSESSID'];
echo $_COOKIE['PHPSESSID'];
require_once('config.php');
require_once('core/login.php');
$config = new Notesconfig();
$baseURL = $config -> baseURL;
$login = new Login();
$connect = $login -> connectDB($config -> host, $config -> user, $config -> password, $config -> db);
if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])) {
$login -> processLogin($connect, $_POST['username'], md5($_POST['password']), $baseURL);
}
if(isset($_GET['logout'])) {
$login -> processLogout($connect, $baseURL);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang='en' xml:lang='en' xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="<?php echo $baseURL; ?>/css/main.css">
</head>
<body class="mainBody">
<div id="container">
<div id="header">
</div>
<div id="content">
<?php
if(!isset($_SESSION['PHPSESSID']) || empty($_SESSION['PHPSESSID']) || !isset($_COOKIE['PHPSESSID']) || empty($_COOKIE['PHPSESSID']) || ($_SESSION['PHPSESSID']) != ($_COOKIE['PHPSESSID'])) {
?>
<div id="main-content" style="width: 960px;">
<?php
$login -> viewLoginForm();
?>
</div>
<?php
}
else {
?>
<div id="main-content" style="width: 710px;">
</div>
<div id="right-column" style="width: 250px;">
<a href="./?logout=true" class="logout" target="_self" >Logout</a>
</div>
<?php
}
?>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
This is my core/login.php :
<?php
class Login {
//Connect Database
public function connectDB($host, $user, $password, $db) {
$connect = mysqli_connect($host, $user, $password, $db); //mysqli_connect(host,username,password,dbname,port,socket);
if($connect) {
echo "Database Connection Established.";
return $connect;
}
else {
echo "Database Connection Failed.";
}
}
//Login User
public function processLogin($connection, $username, $password, $baseURL) {
$username = mysqli_real_escape_string($connection, stripslashes($username));
$password = mysqli_real_escape_string($connection, stripslashes($password));
$db = "SELECT `username`, `password`, `phpsessid` FROM `login` WHERE `username` = '$username' AND `password` = '$password' LIMIT 1";
$db_query = mysqli_query($connection, $db);
if(mysqli_num_rows($db_query)) {
echo "Query Success.";
$row = mysqli_fetch_array($db_query);
$_SESSION['PHPSESSID'] = $row['phpsessid'];
setcookie("PHPSESSID", $row['phpsessid'], 0);
}
else {
echo "Query Failed. Reason:".$connection->error;
return false;
}
mysqli_close($connection);
header('Location: '.$baseURL);
die;
}
//Logout User
public function processLogout($connection, $phpsessid, $baseURL) {
unset($_SESSION['PHPSESSID']);
//unset($_COOKIE['PHPSESSID']);
setcookie("PHPSESSID", $phpsessid, time()-360000);
mysqli_close($connection);
header('Location: '.$baseURL);
}
//Display Login Form
public function viewLoginForm() {
echo '<form action=" " id="loginForm" method="POST" >';
echo '<table class="loginForm">';
echo '<tr>';
echo '<td>Matric No.</td><td><input type=\"text\" name="username" /></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Password</td><td><input type="password" name="password" /></td>';
echo '</tr>';
echo '<tr>';
echo '<td> </td><td><input type="submit" name="login" value="Login" /></td>';
echo '</tr>';
echo '</table>';
echo '</form>';
}
}
?>
The config.php just contains some data I want to use :
<?php
class Notesconfig {
public $baseURL = 'http://localhost/notes';
public $siteName = 'Notes';
public $host = 'localhost';
public $user = 'root';
public $password = '';
public $db = 'notes';
}
?>
However, I need to login twice then successfully set the session and cookies, while I don't need to logout twice.
When I clicked login for the first time, I get Query Success, but not login.
Then I clicked AGAIN the login, and this time I'll successfully login.
After login, I clicked logout, and I return to the login page. And again I need to login twice to successfully login.
How can I solve this error?
EDIT
Change all PHPSESSID and fix the problem.
You are getting value from $_COOKIE in same request after setting it which is not possible. This value will be accessible from the next request so after logging in you have to redirect user (and it's good to redirect after POST request).