Profile page that displays user information from MySQL database - php

I hope someone can be of help. I am trying to get a logged in users information from my sql to display on a profile page. And then for that user to be able to change anything in the fields and save it to update the database.
This is my profile page so far, I'm just not sure on how to implement the php into the form hence why the name php script is sitting at the top.
I am new to all this and have searched about on here for a day now but can't find the answer or be it something I understand. Any help would be really appreciated.
<?
session_start();
include("connection.php");
$query="SELECT name FROM users WHERE id='".$_SESSION['id']."' LIMIT 1";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
$diary=$row['name'];
?>
<!DOCTYPE html>
<html lang="en">
<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>Profile</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com /css?family=Lato:400,300,100,300italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="resources/css/profilestyles.css">
</head>
<body data-spy="scroll" data-target=".navbar-collapse">
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
<a class="navbar-brand">Profile</a> </div>
<div class="collapse navbar-collapse">
<form class="navbar-form navbar-right" method="post">
<ul class="nav nav-pills">
<li role="presentation">My connections</li>
<li role="presentation">World connections</li>
<li role="presentation" class="active">Profile</li>
<li role="presentation">Messages</li>
<li role="presentation">Logout</li>
</ul>
</form>
</div>
</div>
</div>
<div class="container">
<h1>Edit Profile</h1>
<hr>
<div class="row">
<!-- left column -->
<div class="col-md-3">
<div class="text-center"> <img src="//placehold.it/100" class="avatar img-circle" alt="avatar">
<h6>Upload a different photo...</h6>
<input class="form-control" type="file">
</div>
</div>
<!-- edit form column -->
<div class="col-md-9 personal-info">
<div class="alert alert-info alert-dismissable"> <a class="panel-close close" data-dismiss="alert">×</a> <i class="fa fa-coffee"></i> This is an <strong>.alert</strong>. Use this to show important messages to the user. </div>
<h3>Personal info</h3>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-lg-3 control-label name">name:</label>
<div class="col-lg-8">
<input class="form-control" value="" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" value="katie#katie.com" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">DOB:</label>
<div class="col-lg-8">
<input class="form-control" value="yyyy-mm-dd" type="date">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-8">
<input class="form-control" value="America" type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Password:</label>
<div class="col-md-8">
<input class="form-control" value="password" placeholder="At least 8 characters and 1 cap letter" type="password">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Confirm password:</label>
<div class="col-md-8">
<input class="form-control" value="password" placeholder="At least 8 characters and 1 cap letter" type="password">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="button">
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

in the form tag you enter the following code:
form action="edit_profile.php" method="post"
where "edit_profile" is the name of your php file to receive the form data, for each form you one php file, the "method post" It indicates how the data will be sent to the php file
the fields that will be sent to the php you put a name to each like this :
input class="form-control" value="" type="text" **name="name"**
the button of form is submit type. like this:
button **type="submit"** value="save changes"
in the php file:
$name= $_POST['**name**'];
and here all fields of your form.
I hope it helps.

First of all I will sugest to use PDO ( http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers )
The best solution to write souch an applications could be to use some simply framework souch as Yii2 framework ( http://www.yiiframework.com/wiki/?tag=yii2 )
But If you are learning PHP and don't wanna start with a framework I sugest you to use object features and divide you application into files.
The first file that you could create will be the User model class that select and update the user details this class should use the PDO object so I sugest sth like this:
class DB
{
private static $singleton;
public static function getInstance() {
if(is_null(self::$singleton)){
self::$singleton = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '');
}
return self::$singleton;
}
}
class User
{
private $id;
private $name;
private $surname;
public static function find($id)
{
$stmt = DB::getInstance()->prepare("SELECT * FROM users WHERE id=?");
$stmt->execute(array($id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(empty($rows)) {
return null;
}
$user = new self();
$user->id = $rows[0]['id'];
$user->name = $rows[0]['name'];
$user->surname = $rows[0]['surname'];
// And any other
return $user;
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function getSurname()
{
return $this->surname;
}
// And any other
public function update($params)
{
// Shoul also validate the data from user input before store into database
if(isset($params['name']))
{
$this->name = $params['name'];
}
if(isset($params['surname']))
{
$this->surname = $params['surname'];
}
// And any other
$stmt = DB::getInstance()->prepare("UPDATE users SET name = ?, surname = ? WHERE id = ?");
return $stmt->execute(array($this->name, $this->surname, $this->id));
}
}
$user = User::find(1);
$user->update(['name' => 'John']);
// or simply
if($_POST) {
$user->update($_POST);
}
And remember this is not safe method of making app better is to use framework or you must really be carefull when getting data from your users
But I think that this could help you to understood the PHP structure
Then in form :
<input name="surname" class="form-control" value="<?= ($user) ? $user->getSurname() : '' ;?>" type="text">

Related

I'm pretty new to laravel and I'm doing user sign up and login but I'm getting an error

The POST method is not supported for this route. Supported methods: GET, HEAD.
I'm pretty new to laravel and I'm doing user sign up and login but I'm getting an error
This is the controller which is giving an error
namespace App\Http\Controllers;
use Illuminate\Http\facade;
use Request;
use DB;
class hotsmoke extends Controller
{
function login() {
return view('hot_smoke_login');
}
function signup() {
return view('sign-Up');
}
function login2() {
return view('dashboard');
}
function store() {
$uname= Request::input('name');
$uemail = Request::input('email');
$unumber= Request::input('number');
$uaddress= Request::input('address');
$upass= Request::input('password');
DB::unprepared("insert into customers (name, email,number,address,password) values ('$uname','$uemail','$unumber','$uaddress','$upass')");
return redirect('/hot_smoke_login');
}
function match2() {
$uemail = Request::input('email');
$upass = Request::input('password');
$loginData = DB::select('select password from users where email = ?', [$uemail]);
if (count($loginData) > 0){
foreach ($loginData as $tablepass) {
if (($tablepass->password) == $upass){
return view('dashboard');
}
else{
$error='Password does not match';
return view('hot_smoke_login')->with('error',$error);
}
}
}
}
}
my blade view which is not running as mentioned
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hotsmoke</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 p-0" style=" height: 100vh; overflow: hidden;">
<img src="images/hero-img.jpg" alt="" width="100%">
</div>
<div class="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 p-5">
<i class="fa-solid fa-arrow-left backBtn"></i>
<div class="align-items-center justify-content-center d-flex flex-column">
<h3 class="text-white">Login to <strong style="color: #ce913a;">HotSmoke</strong></h3>
<p class="mb-4 secondary-color">We know the cuisines and your taste better than anyone!</p>
<form method="post" id="login">
<div class="form-group first d-flex flex-column">
<label class="primary-color" for="username">Email</label>
<input type="text" class="email" id="username">
</div>
<div class="form-group last mb-3 d-flex flex-column">
<label class="primary-color" for="password">Password</label>
<input type="password" class="email" id="password">
</div>
<div class="d-flex mb-1 align-items-center">
<label class="control control--checkbox mb-0"><span class="caption">Remember me</span>
<input type="checkbox" checked="checked" />
<div class="control__indicator"></div>
</label>
<span class="ml-auto"><a href="forget-password.html" class="forgot-pass" style="color: #e0ae66">Forgot
Password</a></span>
</div>
Do not have an Account?
<small class="text-danger " id="error" style="display: none;"></small>
<br><br>
<button class="email-button">Log In</button>
</form>
</div>
</div>
</div>
</div>
<script src="js/bootstrap.min.js"></script>
<script src="https://kit.fontawesome.com/5e8b9def84.js" crossorigin="anonymous"></script>
<script src="js/login.js"></script>
</body>
</html>
and my routes are
Route::get('sign-Up', [hotsmoke::class, 'signup']);
Route::post('sign-Up', [hotsmoke::class, 'store']);
Route::get('hot_smoke_login', [hotsmoke::class, 'login']);
Route::get('hot_smoke_login', [hotsmoke::class, 'match2']);
please guide me
I hope this will work. In each an every input field add the name attribute and mention the name you want to call it.
For example <input type="text" class="email" name="username"> , do this to every input and after the form tag use #csrf token like this and the route name should be the action,
<form action="/sign-Up" method="post" id="login">
#csrf
...
</form>
I think the first thing you need to do is add an 'action' attribute to your form element which points to the endpoint you want to submit the form to
so in this case it will look like
action="{{ url('/sign-Up') }}"

Trying to UPDATE sql table from html form

I'm grossly underqualified to be trying what I'm trying but I seem to have things going my way until now. I have an issue with my function which seems like it isn't being called when the form submit button is clicked. Apologies if this is formatted poorly. Please see my code below, Thanks
Functions.php
// UP DATE INFO
function settingsUpdate()
{
// call these variables with the global keyword to make them available in function
global $db;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$usernameU = e($_POST['name']);
$numberU = e($_POST['number']);
$id = (isset($_SESSION['user']['id']));
$error = '0';
if($error == 0){
$query = "UPDATE users SET 'username' 'number' WHERE id==$id
VALUES('$usernameU', '$numberU')";
mysqli_query($db, $query);
echo '<div class="alert alert-primary" role="alert">User Settings Updated Successfully.</div>';
} else {
?><div class="alert alert-danger" role="alert">
<p class="text-center"><strong>Oh snap!</strong> Something went wrong, contact us if you think that's wrong.</p>
</div>,<?php
}
}
Settings.php
<!--begin::Form-->
<form id="settings" class="form" method="post">
<!--begin::Card body-->
<div class="card-body border-top p-9">
<!--begin::Input group-->
<div class="row mb-6">
<!--begin::Label-->
<label class="col-lg-4 col-form-label required fw-bold fs-6">Full Name</label>
<!--end::Label-->
<!--begin::Col-->
<div class="col-lg-8">
<!--begin::Row-->
<div class="row">
<!--begin::Col-->
<div class="col-lg-6 fv-row">
<input type="text" name="username" class="form-control form-control-lg form-control-solid mb-3 mb-lg-0" placeholder="Full Name" value="<?php echo $username; ?>" />
</div>
<!--end::Col-->
</div>
<!--end::Row-->
</div>
<!--end::Col-->
</div>
<!--end::Input group-->
<!--begin::Input group-->
<div class="row mb-6">
<!--begin::Label-->
<label class="col-lg-4 col-form-label fw-bold fs-6">
<span class="required">Contact Number</span>
<i class="fas fa-exclamation-circle ms-1 fs-7" data-bs-toggle="tooltip" title="Phone number must be active"></i>
</label>
<!--end::Label-->
<!--begin::Col-->
<div class="col-lg-8 fv-row">
<input type="number" name="number" class="form-control form-control-lg form-control-solid" placeholder="Phone number" value="<?php echo $_SESSION['user']['number']?>" />
</div>
<!--end::Col-->
</div>
<!--end::Input group-->
</div>
<!--end::Card body-->
<!--begin::Actions-->
<div class="card-footer d-flex justify-content-end py-6 px-9">
<button type="submit" class="btn btn-primary" id="settingsUpdate">Save Changes</button>
</div>
<!--end::Actions-->
</form>
<!--end::Form-->
add action attribute in your form element
<form id="settings" class="form" method="post" action="Functions.php">
......
</form>
In your Functions.php create a class and put your function into
$settingUp = new SettingUp($_POST['username'], $_POST['number']);
$settingUp->settingsUpdate();
class SettingUp
{
protected $username;
protected $number;
function __construct($username, $number)
{
$this->username = $username;
$this->number = $number;
}
function settingsUpdate()
{
$usernameU = $this->username;
$numberU = $this->number;
$id = (isset($_SESSION['user']['id']));
//complete the rest of your code
}
}
You can also include your Functions.php in your settings.php and give the name in your submit button
<?php
include('Functions.php');
?>
<form id="settings" class="form" method="post" action="">
......
<button type="submit" class="btn btn-primary" id="settingsUpdate" name="settingsUpdate">Save Changes</button>
</form>
in your Function.php remove the function and modify the code like this
if(isset($_POST['settingsUpdate'])
{
$username = $_POST['username'];
$number = $_POST['number'];
//add the rest of your code
}

Error adding username, email and password in a mysql database with php

I am trying to register users using php. Somehow, the only thing that gets put in is the ID. Mind giving me a tip?
<?php
error_reporting(0);
require_once "php/connect.php";
$username = $_POST ['username'];
$useremail = $_POST['useremail'];
$userpwd = $_POST ['userpwd'];
$userpwd2 = $_POST['userpwd2'];
try {
$statement = $dbconnection->prepare("INSERT INTO `tbl_Nutzerdaten` (userid, username, useremail, userpwd) VALUES (null , '$username', '$useremail', '$userpwd')");
$result = $statement->execute();
$fetch = $statement->fetch();
} catch (PDOException $e) {
echo "Fehler:" . $e->getMessage();
}
?>
So this is what my insert.php looks like. I have been trying around to change my form up but still no success. The database has the table : "tbl_Nutzerdaten" with the columns userid,username,useremail and userpwd. Still i can not add anything except the ID.
<!DOCTYPE html>
<html lang="de">
<head>
<title>Registrierung</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet" >
<script src="js/bootstrap.bundle.min.js" ></script>
<?php
error_reporting(0);
require_once "insert.php";
?>
</head>
<body>
<div class="container bg-transparent border-0">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto border-0">
<div class="img-thumbnail my-5 border-0">
<img src="bilder/htl logo.png"></img>
<div class="card card-signin my-5 border-0">
<div class="card-body border-0">
<form class="form-signin form-control border-0" action="#" method="post">
<div class="form-label-group">
<h1 class="text-center">Registrierung</h1>
<label for="username">Benutzername</label>
<input type="text" id="username" class="form-control text-center" placeholder="Benutzername" required autofocus>
<div class="form-label-group">
<label for="useremail">Email</label>
<input type="email" id="useremail" class="form-control text-center" placeholder="Email" required autofocus>
</div>
</div>
<div class="form-label-group">
<label for="Passwort">Passwort</label>
<input type="password" id="userpwd" class="form-control text-center" placeholder="Passwort" required>
</div>
<div class="form-label-group">
<label for="Passwort2">Passwort bestätigen</label>
<input type="password" id="userpwd2" class="form-control text-center" placeholder="Passwort bestätigen" required>
</div>
<div class="custom-control custom-checkbox mb-3">
<input type="checkbox" class="custom-control-input" id="pwcheck">
<label class="custom-control-label" for="pwcheck">Password merken?</label>
</div>
<button class="btn btn-lg btn-primary btn-block text-uppercase " type="submit">Registrieren</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
And this is the form i am using.
The only thing i see in the Database every time i fill out the form is a ID and empty values.
I would really appreciate the help.
to send data to a specific PHP file you have to define where..
In HTML page in the form tag, the action attribute define the path to your file.php where to send the info.
for example:
<form class="form-signin form-control border-0" action="path/to/your/file.php" method="post">
In your input tags you have to add the "name" attribute, so you can refer to this data in your PHP file with this name... just to be clear with an example...
<input type="text" name="username" id="username" class="form-control text-center" placeholder="Benutzername" required autofocus>
and then in the PHP file take this data with something like this
$username = $_POST ['username'];
Then you have to send the data to a specific database, after all your controls on this data that you want..
To send the data you have to learn how avoid SQL injection with prepared statement, bind parameters and finally execute the statement.
I thinks you have to take a look to all this stuff, I suggest you to see this links:
https://www.php.net/manual/en/book.pdo.php
https://www.w3schools.com/php/php_forms.asp
https://www.w3schools.com/html/html_forms_attributes.asp

How can I add a logout button to my logout page which has security features?

When the user goes to my website after the user logins in on this page they're then presented with this page . However, if I type in the full URL webbrowserinfo.96.lt/logindone/logincode/V1/homepage.php it loads regardless if the user logins in or not. From doing my own tests it has something to do with the log out button.
Therefore, I was thinking I need to do something like this below. However, when I add this code to my protected password page i.e homepage.php it doesn't work i.e nothing happens when I click logout.
<form action="index.php" method="post">
<!-- Logout button -->
<div class="inner_container">
<button class="logout_button" type="submit">Log Out<i class="fas fa-sign-in-alt"></i>
</button>
</div>
</form>
Here is my full code for the password protected code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../../../favicon.ico">
<!-- Site title, CSS external file and font awesome -->
<title>Login Page - Created by Liam Docherty</title>
<link rel="stylesheet" href="css/design.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body class="bg-white">
<div class="container">
<div class="py-5 text-center">
<img class="d-block mx-auto mb-4" src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
<h2>Checkout form</h2>
<p class="lead">Below is an example form built entirely with Bootstrap's form controls. Each required form group has a validation state that can be triggered by attempting to submit the form without completing it.</p>
</div>
<div class="row">
<div class="col-md-4 order-md-2 mb-4">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Your cart</span>
<span class="badge badge-secondary badge-pill">3</span>
</h4>
<ul class="list-group mb-3">
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">Product name</h6>
<small class="text-muted">Brief description</small>
</div>
<span class="text-muted">$12</span>
</li>
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">Second product</h6>
<small class="text-muted">Brief description</small>
</div>
<span class="text-muted">$8</span>
</li>
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">Third item</h6>
<small class="text-muted">Brief description</small>
</div>
<span class="text-muted">$5</span>
</li>
<li class="list-group-item d-flex justify-content-between bg-light">
<div class="text-success">
<h6 class="my-0">Promo code</h6>
<small>EXAMPLECODE</small>
</div>
<span class="text-success">-$5</span>
</li>
<li class="list-group-item d-flex justify-content-between">
<span>Total (USD)</span>
<strong>$20</strong>
</li>
</ul>
<form class="card p-2">
<div class="input-group">
<input type="text" class="form-control" placeholder="Promo code">
<div class="input-group-append">
<button type="submit" class="btn btn-secondary">Redeem</button>
</div>
</div>
</form>
</div>
<div class="col-md-8 order-md-1">
<h4 class="mb-3">Billing address</h4>
<form class="needs-validation" novalidate>
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstName" placeholder="" value="" required>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Last name</label>
<input type="text" class="form-control" id="lastName" placeholder="" value="" required>
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="username">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">#</span>
</div>
<input type="text" class="form-control" id="username" placeholder="Username" required>
<div class="invalid-feedback" style="width: 100%;">
Your username is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email <span class="text-muted">(Optional)</span></label>
<input type="email" class="form-control" id="email" placeholder="you#example.com">
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="34 Hoxton liam street" required>
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="row">
<div class="col-md-5 mb-3">
<!-- Logout button -->
<a class="btn btn-primary" href="index.php" role="button">Signout button</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
My website has three scripts here they're if you need to see them
BELOW IS THE LOGIN PAGE CODE
<?php
//PHP method to use cache memory to store details
session_start();
//Makes the "config.php" file available to be executed from this page
require_once('dbconfig/config.php');
?>
<!DOCTYPE html>
<html>
<head>
<!-- Site title, CSS external file and font awesome -->
<title>Login Page - Created by Liam Docherty</title>
<link rel="stylesheet" href="css/design.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>
<body>
<div id="main-wrapper">
<center>
<h2>Login Form - Created by Liam Docherty</h2>
</center>
<div class="imgcontainer">
<img src="imgs/icon-person-512.png" alt="Avatar" class="avatar">
</div>
<!-- THE FORM -->
<!-- action="index.php" -- This attribute shows where the PHP script that does the processing is located -->
<!-- method="post" -- The attribute identifies the action that will be performed with the data of the form. I.E. POST data to the "users" database -->
<form action="index.php" method="post">
<div class="inner_container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<!-- The Login button -->
<button class="login_button" name="login" type="submit">Login</button>
<!-- The button that is linked to the "register.php" page -->
<button type="button" class="register_btn">Register</button>
</div>
</form>
<?php
//Condition, checking the Login button is pressed
if(isset($_POST['login']))
{
//The data from the Form (username & password) is stored into the #$username & #$passwordVariables
//You use # before a VARIABLE in PHP when you do not want to initialise the VARIABLE before using it
#$username=$_POST['username'];
#$password=$_POST['password'];
//Statement that will SELECT the data from the "login" table, WHERE the Usename and Password typed match the typed ones
//Once the database is checked, if login details match than it stores the data in the "$query" VARIABLE
$query = "SELECT * FROM login WHERE username='$username' and password='$password' ";
//echo $query;
//This statement performs both the connection to the database using the values in the "$con" VARIABLE and
//The SELECT statement stored in the "$query" VARIABLE
$query_run = mysqli_query($con,$query);
//echo mysql_num_rows($query_run);
//IF the "$query_run" is run successfully, then
if($query_run)
{
//Check if the Username and Password exist in the database, if they exist
if(mysqli_num_rows($query_run)>0)
{
$row = mysqli_fetch_array($query_run,MYSQLI_ASSOC);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//Sent the user to the "homepage.php" page
header( "Location: homepage.php");
}
else
{
//IF NOT, Display the message below
echo '<script type="text/javascript">alert("No such User exists. Invalid Credentials")</script>';
}
}
//IF the "$query_run" is NOT successful, then
else
{
//Display this message
echo '<script type="text/javascript">alert("Database Error")</script>';
}
}
else
{
}
?>
</div>
</body>
</html>
MY OWN UPDATED ATTEMPT BASED ON HELP
This issue with the code below is that it doesn't let me actually login. This is good though as it stops a user just typing in the full file path of the URL and bypassing the login system.
<?php
//check if session id is set. If it is not set, user will be redirected back to login page
if(!isset($_SESSION['username'])){
header('Location:index.php');
die();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../../../favicon.ico">
<!-- Site title, CSS external file and font awesome -->
<title>Login Page - Created by Liam Docherty</title>
<link rel="stylesheet" href="css/design.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body class="bg-white">
<div class="container">
<div class="py-5 text-center">
<img class="d-block mx-auto mb-4" src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
<h2>Checkout form</h2>
<p class="lead">Below is an example form built entirely with Bootstrap's form controls. Each required form group has a validation state that can be triggered by attempting to submit the form without completing it.</p>
</div>
<div class="row">
<div class="col-md-4 order-md-2 mb-4">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Your cart</span>
<span class="badge badge-secondary badge-pill">3</span>
</h4>
<ul class="list-group mb-3">
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">Product name</h6>
<small class="text-muted">Brief description</small>
</div>
<span class="text-muted">$12</span>
</li>
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">Second product</h6>
<small class="text-muted">Brief description</small>
</div>
<span class="text-muted">$8</span>
</li>
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">Third item</h6>
<small class="text-muted">Brief description</small>
</div>
<span class="text-muted">$5</span>
</li>
<li class="list-group-item d-flex justify-content-between bg-light">
<div class="text-success">
<h6 class="my-0">Promo code</h6>
<small>EXAMPLECODE</small>
</div>
<span class="text-success">-$5</span>
</li>
<li class="list-group-item d-flex justify-content-between">
<span>Total (USD)</span>
<strong>$20</strong>
</li>
</ul>
<form class="card p-2">
<div class="input-group">
<input type="text" class="form-control" placeholder="Promo code">
<div class="input-group-append">
<button type="submit" class="btn btn-secondary">Redeem</button>
</div>
</div>
</form>
</div>
<div class="col-md-8 order-md-1">
<h4 class="mb-3">Billing address</h4>
<form class="needs-validation" novalidate>
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstName" placeholder="" value="" required>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Last name</label>
<input type="text" class="form-control" id="lastName" placeholder="" value="" required>
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="username">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">#</span>
</div>
<input type="text" class="form-control" id="username" placeholder="Username" required>
<div class="invalid-feedback" style="width: 100%;">
Your username is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email <span class="text-muted">(Optional)</span></label>
<input type="email" class="form-control" id="email" placeholder="you#example.com">
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="34 Hoxton liam street" required>
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="row">
<div class="col-md-5 mb-3">
<!-- Logout button -->
<a class="btn btn-primary" href="index.php" role="button">Signout button</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
The following is a very simple solution for your logout functionality for the purpose of a school/college assignment.
A "live" production website will need a lot of security in the login system (but that is a whole other topic).
I can see you know this already so i'll continue with my solution ;)
Firstly the logout form you did was a great idea well done. But I think it didn't work because I've noticed you haven't closed the <form> tag for your "Billing address" form within your homepage.php so you should do that before anything else.
Here's my advice on the full structure. Hope it helps :)
homepage.php
Add php to the top of the homepage above the <!doctype html> to check if the username is set and if not redirect to the index/login page.
Add an HTML form to the homepage with a "sign out" submit button which will redirect to the login/index page when submitted.
(Make sure you put this form outside any other forms.)
Add a javaScript function called confirmLogOut to the homepage which will prompt the user to confirm they wish to log out.
So you should add the following code to your homepage.php (fit it in to your code where i've demonstarted-hopefully it's clear)
<?php
//start the session
session_start();
//If the user is not logged in, send them to the index/login page
if(!isset($_SESSION['username'])){
header('Location: index.php');
exit();
}
?>
<!doctype html>
<html lang="en">
<head>
<script>
//javaScript function for prompting user to confirm they want to log out.
//This will be executed when the signout button is pressed.
function confirmLogOut(){
var confirmation = confirm("Are you sure you want to log out?");
if(confirmation){
//the user has confirmed they would like to log out so we submit the form
//ie return true
return true;
}else{
//the user has canceled their log out request so we don't submit the form
return false;
}
}
</script>
</head>
<body>
<!--Log out/sign out button form-->
<!--When the following form is submitted we called the confirmLogOut javaScript function in order to prompt the
user to confirm they wish to log out before redirecting to the index/login page-->
<form id="form-log-out" method="post" action="index.php" onsubmit="return confirmLogOut()">
<input name="log_out" type="hidden" value="1"/>
<input type="submit" class="btn btn-primary" value="Signout button" />
</form>
</body>
</html>
index.php
This is the full php code which should be at the top of your login/index page
<?php
//PHP method to use cache memory to store details
session_start();
//Makes the "config.php" file available to be executed from this page
require_once('dbconfig/config.php');
if(isset($_POST["log_out"]) && ($_POST["log_out"] == '1')) {
//the log_out post variable is set and is equal to 1.
//This means we have come from another page after pressing the log out button.
//unset all session values
$_SESSION = array();
//Destroy the session
session_destroy();
}
?>
Sorry if I am not explaining very well. First, you need to set a session id for the users and create a if statement to check if they are set for pages that you do not want to reveal for unauthorized users.
e.g
//check if session id is set. If it is not set, user will be redirected back to login page
if(!isset($_SESSION['username'])){
header('Location:index.php');
die();
}
else
// send authorized users to homepage.
{
header('Location:homepage.php');
}
You have to kill sessions as well after logging out and you can do it by the following:
unset($_SESSION['username']);
// kill session
session_destroy();
// send user back to login page.
header("Location: index.php");
Hope it helps!

Codeigniter : Form became weird when using select option (form_dropdown) to edit my data

It's work fine when I am inputing data using select option on CI but when I try to edit or update my data again my form became weird like this (See picture edit form)
Here my controller :
public function updateobat ($kode_obat){
if($_POST==null){
$this->load->model('a_model');
$data['hasil'] = $this->a_model->select2($kode_obat);
$data['title'] = "Data Stok Obat | Praktik Dokter Umum";
$data['tb_jenisobat'] = $this->a_model->ambil_jenisobat();
$this->template->admin('admin/edit-obat',$data);
}else{
$this->load->model('a_model');
$this->a_model->update_obat($kode_obat);
$data['title'] = "Data Stok Obat | Praktik Dokter Umum";
$data['obat'] = $this->a_model->ambil_obat();
$this->template->admin('admin/data-obat',$data);
}
}
Model
public function update_obat($kode_obat){
$nama_obat = $this->input->post('nama_obat');
$kode_jenis_obat = $this->input->post('kode_jenis_obat');
$stok= $this->input->post('stok');
$data = array('nama_obat' => $nama_obat,
'kode_jenis_obat' => $kode_jenis_obat,
'stok' => $stok,
);
$this->db->where('kode_obat',$kode_obat);
$this->db->update('tb_obat',$data);
}
public function select2($kode_obat){
return $this->db->get_where('tb_obat', array('kode_obat' => $kode_obat))->row();
}
View
<!-- Main content -->
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-md-8">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Silahkan melakukan edit stok obat</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="<?php echo base_url().'index.php/a_controller/updateobat/'.$hasil->kode_obat; ?>" method="post">
<div class="box-body">
<div class="form-group">
<label for="exampleInputNama">Nama Obat</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-medkit"></i></span>
<input type="text" class="form-control" name="nama_obat" id="exampleInputNama" placeholder="Nama Obat" action="<?php echo form_input('nama_obat',$hasil->nama_obat);?>">
</div>
</div>
<div class="form-group">
<label for="exampleInputJenis">Jenis Obat</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-list"></i></span>
<select name="kode_jenis_obat" class="form-control" action="<?php echo form_dropdown('kode_jenis_obat',$hasil->kode_jenis_obat);?>">
<option value="none" selected="selected">Pilih Jenis Obat</option>
<!-----Displaying fetched cities in options using foreach loop ---->
<?php foreach($tb_jenisobat as $jenisobat):?>
<option value="<?php echo $jenisobat->kode_jenis_obat?>"><?php echo $jenisobat->nama_jenis_obat?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="form-group">
<label for="exampleInputUsername">Stok Obat</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-list"></i></span>
<input type="text" class="form-control" name="stok" id="exampleInputUsername" placeholder="Stok" action="<?php echo form_input('stok',$hasil->stok);?>">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<!-- /.box -->
</div>
</div>
<!-- /.row -->
</section>
I am using form_dropdown for my select option
I think there is something wrong with my controller syntax?
$data['tb_jenisobat'] = $this->a_model->ambil_jenisobat();
But I am not sure enough, can someone help me?
Picture : edit form

Categories