How can I edit/update an element in xml file using php? - php

I am trying to edit the information for a user and then save that new information to the xml file to display on another page but the updates are not being saved.
Here is the php code to edit a user:
<?php
require 'simplexml.class.php';
$users=simplexml_load_file('UserList.xml');
if (isset($_POST['savebutton']))
{ foreach ($users->user as $user){
if($user['firstName']==$_POST['firstName']){
$user->firstName= $_POST['firstName'];
$user->lastName= $_POST['lastName'];
$user->email= $_POST['email'];
$user->password= $_POST['password'];
$user->address= $_POST['address'];
$user->number= $_POST['number'];
break;
}
}
file_put_contents('UserList.xml', $users->asXML('UserList.xml'));
header('location: P9.php');
}
foreach ($users->user as $user){
if($user['firstName']==$_GET['firstName']){
$firstName= $user->firstName;
$lastName= $user->lastName;
$email= $user->email;
$password= $user->password;
$address= $user->address;
$number= $user->number;
break;
}
}
?>
<!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.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="style2.css">
<link rel="stylesheet" href="Main-Stylesheet.css">
</head>
<body>
<!--header-->
<nav class="navbar nav_bar justify-content-between">
<a class="nav_logo" href="index.html">
<img src="Images/Logo.png">
</a>
<form class="search">
<input class="search_bar" type="search" placeholder="'Product'">
<button class="search_button" type="submit">Search</button>
</form>
<a class="cart_button" href="ShoppingCart.html">
<div class="cart_circle">
<img src="Images/cart-logo.png" />
</div>
</a>
</nav>
<!--Content-->
<div class="container-fluid">
<div class="row">
<nav id="sidebarMenu" class="col-12 col-md-3 col-lg-2 bg-light sidebar">
<div class="position-sticky pt-3">
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="P7.html">
Products
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="P11.html">
Orders
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="P9.html">
User List
</a>
</li>
</ul>
</div>
</nav>
<form method="POST" action="P9.php">
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Edit User</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<button type="submit" class="btn btn-sm btn-primary" name="savebutton">
Save
</button>
</div>
</div>
<div class="row">
<div class="col">
<input type="text" class="form-control" placeholder="First name" aria-label="First name" name="firstName" value="<?php echo $firstName; ?>">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Last name" aria-label="Last name" name="lastName" value="<?php echo $lastName; ?>">
</div>
</div>
<br>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="name#example.com" name="email" value="<?php echo $email; ?>">
</div>
<div class="mb-3">
<label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" name="password" value="<?php echo $password; ?>">
</div>
</div>
<br>
<div class="col-12">
<label for="inputAddress" class="form-label">Address</label>
<input type="text" class="form-control" id="inputAddress" name="address" placeholder="1234 Main St" value="<?php echo $address; ?>">
</div>
<br>
<div class="col-12">
<label for="inputAddress" class="form-label">Phone Number</label>
<input type="text" class="form-control" id="inputAddress" name="number" placeholder="i.e. 123456" value="<?php echo $number; ?>">
</div>
</form>
</main>
<!-- footer section -->
<div class="col-12 row h-100 nopadding footer">
<div class="col-4 row footer-heading nopadding about">
<h2>About Us</h2>
Our Story
Blog
Customers
</div>
<div class="col-4 row footer-heading nopadding contact-form">
<h2>Customer Service</h2>
Contact Us
Terms and Conditions
Find a Store
FAQ
</div>
<div class="col-4 row footer-heading nopadding social-media">
<h2>Social Media</h2>
Instagram
Facebook
YouTube
Twitter
</div>
<div class="col-12 row nopadding">
<div class="col-2 footer-bottom footer">
© 2022 poeatry.com
</div>
<div class="col-5">
</div>
</div>
</div>
<!-- footer section -->
</body>
</html>
Here is the xml file:
<?xml version="1.0"?>
<UserList>
<info>
<FirstName> </FirstName>
<LastName> </LastName>
<Email> </Email>
<Password> </Password>
<Address> </Address>
<Number> </Number>
</info>
</UserList>
Currently when i click on the edit button from my display page it shows me the correct item but the new information updated is never saved to the xml.

Currently, posted XML does not have a <user> node which you iterate on but <info> node. Simply adjust your path to actual tag. Additionally, XML tag names are case sensitive (i.e., firstName != FirstName). Even better, name PHP variables in line with XML nodes.
Also, consider escaping user input for special XML entities with htmlspecialchars to ensure legal XML.
require 'simplexml.class.php';
$userList = simplexml_load_file('UserList.xml');
if (isset($_POST['savebutton'])) {
foreach ($userList->info as $info) {
if((string)$info->FirstName == $_POST['firstName']) {
$info->FirstName = htmlspecialchars($_POST['firstName']);
$info->LastName = htmlspecialchars($_POST['lastName']);
$info->Email = htmlspecialchars($_POST['email']);
$info->Password = htmlspecialchars($_POST['password']);
$info->Address = htmlspecialchars($_POST['address']);
$info->Number = htmlspecialchars($_POST['number']);
break;
}
}
$userList->asXML('UserList.xml');
header('location: P9.php');
}

The PHP code for recording data refers to UserList's child node as user, but your XML code calls it info.
Since the SimpleXMLElement Object does not have a child node called user, it returns an empty object. SimpleXML doesn't trigger an exception for calling a node that doesn't exist so it wouldn't show up in the error log. The code would just proceed and nothing would get saved.
This should work:
foreach ($users->info as $user){
if($user['firstName']==$_POST['firstName']){
$user->firstName= $_POST['firstName'];
$user->lastName= $_POST['lastName'];
$user->email= $_POST['email'];
$user->password= $_POST['password'];
$user->address= $_POST['address'];
$user->number= $_POST['number'];
break;
}
}
or you could change the XML document to:
<?xml version="1.0"?>
<UserList>
<user>
<FirstName> </FirstName>
<LastName> </LastName>
<Email> </Email>
<Password> </Password>
<Address> </Address>
<Number> </Number>
</user>
</UserList>

Related

Empty data is submitted to database, how can I fix it?

I'm making a website about a sushi restaurant which includes a form page of which the data is submitted to the database. I've written the code of it and the insertion to the database also works but the problem is that the data in the database is empty, even if I filled out all fields of the form and clicked on the submit button. I've checked my code and it looks correct and I've also tried messing with the PHP code but without success. I've also asked this question on a Discord server and someone told me that the error could be in the HTML code except I really don't know what's wrong with my HTML code. Here's my code: https://jsfiddle.net/qrsaegkc/
Do you guys see what I do wrong and/or how I can solve this?
Thanks in advance and all help is appreciated!
Code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$firstName = "";
$lastName = "";
$emailAdress = "";
$deliveryAdress = "";
$postalCode = "";
$residencePlace = "";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "zuzu";
try {
if(isset($_POST["firstName"])) {
$firstName = $_POST["firstName"];
}
if(isset($_POST["lastName"])) {
$lastName = $_POST["lastName"];
}
if(isset($_POST["emailAdress"])) {
$emailAdress = $_POST["emailAdress"];
}
if(isset($_POST['deliveryAdress'])) {
$deliveryAdress = $_POST['deliveryAdress'];
}
if(isset($_POST['postalCode'])) {
$postalCode = $_POST['postalCode'];
}
if(isset($_POST['residencePlace'])) {
$residencePlace = $_POST['residencePlace'];
}
$database = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$st = $database->prepare("INSERT INTO customer (f_name, l_name, email, address, postal_code, city) VALUES (:firstName, :lastName, :emailAdress, :deliveryAdress, :postalCode, :residencePlace)");
$st->bindParam(':firstName', $firstName);
$st->bindParam(':lastName', $lastName);
$st->bindParam(':emailAdress', $emailAdress);
$st->bindParam(':deliveryAdress', $deliveryAdress);
$st->bindParam(':postalCode', $postalCode);
$st->bindParam(':residencePlace', $residencePlace);
$st->execute();
echo "Form submission successful!";
}
catch(PDOException $error) {
echo "Error: " . $error->getMessage();
}
$database = null;
?>
<!DOCTYPE HTML>
<head>
<meta name= "viewport" content= "width=device-width, initial-scale= 1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Kaushan+Script&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Kiwi+Maru&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href= "/Project%20Zuzu/CSS%20Documents/Zuzu%20Style%20(Riza%20Incedal%20version)%20(Customer%20Details%20version).css">
<link rel= "stylesheet" href= "/Project%20Zuzu/CSS%20Documents/Zuzu%20Style%20(Riza%20Incedal%20version).css">
</head>
<body>
<!--Header-->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class= "navbar-brand text-white fw-bold logo">Zuzu</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="true" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse show" id="navbarColor01">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link text-white" aria-current="page" href="/Project%20Zuzu/PHP%20Files/Zuzu%20Homepage%20(Riza%20Incedal%20version).php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="/Project%20Zuzu/PHP%20Files/Zuzu%20Sushi%20page%20(Riza%20Incedal%20version).php">Order</a>
</li>
</ul>
</div>
</div>
</nav>
<img class="w-100 image-resize" src= "/Project%20Zuzu/Images/Sushi%20banner%20image.jpg">
<!--Main-->
<div class= "container">
<h2 class="fw-bold position-relative heading1">Customer details</h2>
<div class="mb-3">
<form class= "submissionForm position-relative" action= "/PHP%20Files/Zuzu%20Customer%20overview%20(Riza%20Incedal%20Version).php" method= "POST">
<div class="col-md-4 w-100 position-relative input7">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" value="" name="firstName" id= "firstName" required>
</div>
<div class="col-md-4 w-100 position-relative input8">
<label for="lastName" class="form-label">Last name</label>
<input type="text" class="form-control" value="" name="lastName" id= "lastName" required>
</div>
<div class="col-md-6 w-100 position-relative input9">
<label for="emailAdress" class="form-label">Email</label>
<input type="text" class="form-control" name= "emailAdress" id= "emailAdress" required>
</div>
</div>
<div class="col-md-6 w-100 position-relative input10">
<label for="deliveryAdress" class="form-label">Adress</label>
<input type="text" class="form-control" name= "deliveryAdress" id= "deliveryAdress" required>
</div>
<div class="col-md-3 w-100 position-relative input11">
<label for="postalCode" class="form-label">Postal code</label>
<input type="text" class="form-control" name= "postalCode" id= "postalCode" required>
</div>
<div class="col-md-3 w-100 position-relative input12">
<label for="residencePlace" class="form-label">Place of residence</label>
<input type="text" class="form-control" name= "residencePlace" id= "residencePlace" required>
</div>
<div class="col-12 w-100">
<button type="submit" class="btn btn-dark button1" name="subButton" value= "Submit">Submit</button>
</div>
</div>
</form>
<!--Footer-->
<footer class="bg-dark text-center text-white footer">
<div class="container p-4">
<div class="row d-flex justify-content-center">
</div>
</form>
</section>
<div class="row">
<div class="col">
<p><b>Contact</b><br>
Zuzu <br>
Kalealtı Caddesi 63,<br>
63420 <a class= "link1" href="https://en.wikipedia.org/wiki/Birecik">Birecik</a> <br>
zuzu.birecik#gmail.com <br>
+904141516151</p>
</div>
<div class= "col"><b>Opening hours</b> <br>
Monday: 09:00 - 00:00 <br>
Tuesday: 09:00 - 00:00 <br>
Wednesday: 09:00 - 00:00 <br>
Thursday: 09:00 - 00:00 <br>
Friday: 09:00 - 00:00 <br>
Saturday: 09:00 - 00:00 <br>
Sunday: 09:00 - 00:00 <br>
</div>
</div>
</section>
</div>
<div class="text-center p-3">
<p class="text-white" > Copyright © 2022 Riza Incedal</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</body>
</html>

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!

How to save the updated total of stocks after it minus ? [php-json]

How to save the updated total of stocks after it minus ? [php-json]
i need to get the current stocks and minus it to the quantity bought by the customer. and it will post to the order.json and get the total payment and
i need to update the food.json for the stocks and to put the orderlist on order.json
This is the code to get the value of buy product but the quantity entered by the customer do not minus on the stocks and do not get the total. I think there is wrong in my codes. Please Help me. Im just a beginner to json
<?php
if (isset($_GET["id"])) {
$id = (int) $_GET["id"];
$getfile = file_get_contents('food.json');
$jsonfile = json_decode($getfile, true);
$jsonfile = $jsonfile["records"];
$jsonfile = $jsonfile[$id];
}
if (isset($_POST["id"])) {
$id = (int) $_POST["id"];
$getfile = file_get_contents('food.json');
$all = json_decode($getfile, true);
$jsonfile = $all["records"];
$jsonfile = $jsonfile[$id];
$quan = $_POST['quan'];
$stocks = $stocks - $quan; // on minusing the stocks :<
$post["pname"] = isset($_POST["pname"]) ? $_POST["pname"] : "";
$post["price"] = isset($_POST["price"]) ? $_POST["price"] : "";
$post["stocks"] = isset($_POST["stocks"]) ? $_POST["stocks"] : "";
// $post["quan"] = isset($_POST["quan"]) ? $_POST["quan"] : "";
if ($jsonfile) {
unset($all["records"][$id]);
$all["records"][$id] = $post;
$all["records"] = array_values($all["records"]);
file_put_contents("food.json", json_encode($all));
}
header("Location:index_crudjson.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="tutorial-boostrap-merubaha-warna">
<meta name="author" content="ilmu-detil.blogspot.com">
<title></title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<style type="text/css">
.navbar-default {
background-color: #3b5998;
font-size:18px;
color:#ffffff;
}
</style>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<h4>JSON Bake Shop</h4>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
</div>
</div>
</nav>
<!-- /.navbar -->
<div class="container">
<div class="row">
<div class="row">
<h3>Buy a Product</h3>
</div>
<?php if (isset($_GET["id"])): ?>
<form method="POST" action="buy.php">
<div class="col-md-6">
<input type="hidden" value="<?php echo $id ?>" name="id"/>
<div class="form-group">
<label for="inputFName">Product Name</label>
<input type="text" class="form-control" required="required" id="inputFName" value="<?php echo $jsonfile["pname"] ?>" name="pname" placeholder="Product Name">
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="inputLName">Price</label>
<input type="number" class="form-control" required="required" id="inputLName" value="<?php echo $jsonfile["price"] ?>" name="price" placeholder="Price">
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="inputAge">Stocks</label>
<input type="number" required="required" class="form-control" id="inputAge" value="<?php echo $jsonfile["stocks"] ?>"
name="stocks" placeholder="Stocks">
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="inputAge">Quantity</label>
<input type="number" required="required" class="form-control" id="inputAge" value="<?php echo $jsonfile["quan"] ?>"
name="quan" placeholder="Quantity">
<span class="help-block"></span>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-warning">Buy</button>
<a class="btn btn btn-default" href="index_crudjson.php">Back</a>
</div>
</div>
</form>
<?php endif; ?>
</div> <!-- /row -->
</div> <!-- /container -->
</body>
</html>
This is the attached sample of order.json, food.json, index and buy.phpsample picturefood.json
You have a simple error on you $post assignment
$post["stocks"] = $stocks;
I could not understand clearly your logic, but $stocks is not used at all, and the real stocks value should not be in $_POST.

PHP doesn't post form values after migrating login page [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I've decided to change the design on our login page, however there is a issue.
In the new login page nothing pass after I press the login button however on the old page it still works as before.
Old page:
<?php
require_once('./files/functions.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Social Panel">
<link rel="shortcut icon" href="images/favicon.png">
<title><?php echo($WebsiteName); ?> | Sign In</title>
<link href="bs3/css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-reset.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<!--[if lt IE 9]>
<script src="js/ie8-responsive-file-warning.js"></script><![endif]-->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body class="login-body">
<div class="container">
<form class="form-signin" method="POST">
<h2 class="form-signin-heading">sign in now</h2>
<div class="login-wrap">
<div class="user-login-info">
<input type="text" name="email" class="form-control" placeholder="User Name" autofocus required>
<input type="password" name="password" class="form-control" placeholder="Password" required>
</div>
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
<span class="pull-right">
<a data-toggle="modal" href="#myModal"> Forgot Password?</a>
</span>
</label>
<input type="submit" name="login" value="Sign In" class="btn btn-lg btn-login btn-block">
<div class="registration">
Don't have an account yet?
<a class="" href="registration.php">Create an account</a>
</div>
</div>
</form>
<?php
if(isset($_POST['login'])) {
if(isset($_POST['email']) && isset($_POST['password']) &&
is_string($_POST['email']) && is_string($_POST['password']) &&
!empty($_POST['email']) && !empty($_POST['password'])) {
$email = stripslashes(strip_tags($_POST['email']));
$password = md5($_POST['password']);
$stmt = $pdo->prepare('SELECT * FROM users WHERE UserEmail = :UserEmail');
$stmt->bindParam(':UserEmail', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$stmt = $pdo->prepare('SELECT * FROM users WHERE UserEmail = :UserEmail AND UserPassword = :UserPassword');
$stmt->execute(array(':UserEmail' => $email, ':UserPassword' => $password));
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$UserLevel = $row['UserLevel'];
if($UserLevel == 'banned') {
$display->ReturnError('Your account has been suspended.');
return false;
}
$UserID = $row['UserID'];
$time = time();
$IPAddress = $_SERVER['REMOTE_ADDR'];
$_SESSION['auth'] = $UserID;
$stmt = $pdo->prepare('INSERT INTO logs (LogUserID, LogDate, LogIPAddress) VALUES (:LogUserID, :LogDate, :LogIPAddress)');
$stmt->execute(array(':LogUserID' => $UserID, ':LogDate' => $time, ':LogIPAddress' => $IPAddress));
$display->ReturnSuccess('You was successfully logged in.');
$settings->forceRedirect('index.php', 2);
} else {
$display->ReturnError('Invalid user credentials.');
}
} else {
$display->ReturnError('User with these credentials does not exists.');
}
}
}
?>
</div>
<script src="js/jquery.js"></script>
<script src="bs3/js/bootstrap.min.js"></script>
<script src="js/sm-requests.js"></script>
<div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="myModal" class="modal fade">
<form method="POST">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Forgot Password ?</h4>
</div>
<div class="modal-body">
<p>Enter your user name below.</p>
<input type="text" id="username" name="username" placeholder="User Name" class="form-control placeholder-no-fix" autocomplete="off" required>
</div>
<div class="modal-body">
<p>Enter your e-mail address below.</p>
<input type="email" id="email" name="email" placeholder="Email" class="form-control placeholder-no-fix" autocomplete="off" required>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
<button id="reset" class="btn btn-success" type="button">Reset</button>
<hr>
<div id="result"></div>
</div>
</div>
</div>
</form>
</div>
</body>
</html>
New Page:
<?php
require_once('./files/functions.php');
?>
<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>log in</title>
<!-- Vendors -->
<!-- Animate CSS -->
<link href="vendors/bower_components/animate.css/animate.min.css" rel="stylesheet">
<!-- Material Design Icons -->
<link href="vendors/bower_components/material-design-iconic-font/dist/css/material-design-iconic-font.min.css" rel="stylesheet">
<!-- Site CSS -->
<link href="css/app-1.min.css" rel="stylesheet">
</head>
<body>
<div class="login">
<form action="" >
<!-- Login -->
<div class="login__block toggled" id="l-login">
<div class="login__block__header">
<i class="zmdi zmdi-account-circle"></i>
Hi there! Please Sign in
<div class="actions login__block__actions">
<div class="dropdown">
<i class="zmdi zmdi-more-vert"></i>
<ul class="dropdown-menu pull-right">
<li><a data-block="#l-register" href="#">Create an account</a></li>
<li><a data-block="#l-forget-password" href="#">Forgot password?</a></li>
</ul>
</div>
</div>
</div>
<div class="login__block__body">
<form action="" >
<div class="form-group form-group--float form-group--centered form-group--centered">
<input type="text" class="form-control" name="email">
<label>Email Address</label>
<i class="form-group__bar"></i>
</div>
<div class="form-group form-group--float form-group--centered form-group--centered">
<input type="password" class="form-control" name="password">
<label>Password</label>
<i class="form-group__bar"></i>
</div>
<button name="login" class="btn btn--light btn--icon m-t-15"><i class="zmdi zmdi-long-arrow-right"></i></button>
</form>
</div>
<?php
if(isset($_POST['login'])) {
if(isset($_POST['email']) && isset($_POST['password']) &&
is_string($_POST['email']) && is_string($_POST['password']) &&
!empty($_POST['email']) && !empty($_POST['password'])) {
$email = stripslashes(strip_tags($_POST['email']));
$password = md5($_POST['password']);
$stmt = $pdo->prepare('SELECT * FROM users WHERE UserEmail = :UserEmail');
$stmt->bindParam(':UserEmail', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$stmt = $pdo->prepare('SELECT * FROM users WHERE UserEmail = :UserEmail AND UserPassword = :UserPassword');
$stmt->execute(array(':UserEmail' => $email, ':UserPassword' => $password));
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$UserLevel = $row['UserLevel'];
if($UserLevel == 'banned') {
$display->ReturnError('Your account has been suspended.');
return false;
}
$UserID = $row['UserID'];
$time = time();
$IPAddress = $_SERVER['REMOTE_ADDR'];
$_SESSION['auth'] = $UserID;
$stmt = $pdo->prepare('INSERT INTO logs (LogUserID, LogDate, LogIPAddress) VALUES (:LogUserID, :LogDate, :LogIPAddress)');
$stmt->execute(array(':LogUserID' => $UserID, ':LogDate' => $time, ':LogIPAddress' => $IPAddress));
$display->ReturnSuccess('You was successfully logged in.');
$settings->forceRedirect('index.php', 2);
} else {
$display->ReturnError('Invalid user credentials.');
}
} else {
$display->ReturnError('User with these credentials does not exists.');
}
}
}
?>
</form>
</div>
<!-- Register -->
<div class="login__block" id="l-register">
<div class="login__block__header palette-Blue bg">
<i class="zmdi zmdi-account-circle"></i>
Create an account
<div class="actions login__block__actions">
<div class="dropdown">
<i class="zmdi zmdi-more-vert"></i>
<ul class="dropdown-menu pull-right">
<li><a data-block="#l-login" href="#">Already have an account?</a></li>
<li><a data-block="#l-forget-password" href="#">Forgot password?</a></li>
</ul>
</div>
</div>
</div>
<div class="login__block__body">
<div class="form-group form-group--float form-group--centered">
<input type="text" class="form-control">
<label>Name</label>
<i class="form-group__bar"></i>
</div>
<div class="form-group form-group--float form-group--centered">
<input type="text" class="form-control">
<label>Email Address</label>
<i class="form-group__bar"></i>
</div>
<div class="form-group form-group--float form-group--centered">
<input type="password" class="form-control">
<label>Password</label>
<i class="form-group__bar"></i>
</div>
<div class="input-centered">
<div class="checkbox">
<label>
<input type="checkbox" value="">
<i class="input-helper"></i>
Accept the license agreement
</label>
</div>
</div>
<button class="btn btn--light btn--icon m-t-15"><i class="zmdi zmdi-plus"></i></button>
</div>
</div>
<!-- Forgot Password -->
<div class="login__block" id="l-forget-password">
<div class="login__block__header palette-Purple bg">
<i class="zmdi zmdi-account-circle"></i>
Forgot Password?
<div class="actions login__block__actions">
<div class="dropdown">
<i class="zmdi zmdi-more-vert"></i>
<ul class="dropdown-menu pull-right">
<li><a data-block="#l-login" href="#">Already have an account?</a></li>
<li><a data-block="#l-register" href="#">Create an account</a></li>
</ul>
</div>
</div>
</div>
<div class="login__block__body">
<p class="m-t-30">Lorem ipsum dolor fringilla enim feugiat commodo sed ac lacus.</p>
<div class="form-group form-group--float form-group--centered">
<input type="text" class="form-control">
<label>Email Address</label>
<i class="form-group__bar"></i>
</div>
<button class="btn btn--light btn--icon m-t-15"><i class="zmdi zmdi-check"></i></button>
</div>
</div>
</div>
<!-- Older IE Warning -->
<!--[if lt IE 9]>
<div class="ie-warning">
<h1>Warning!!</h1>
<p>You are using an outdated version of Internet Explorer, please upgrade <br/>to any of the following web browsers to access this website.</p>
<div class="ie-warning__container">
<ul class="ie-warning__download">
<li>
<a href="http://www.google.com/chrome/">
<img src="img/browsers/chrome.png" alt="">
<div>Chrome</div>
</a>
</li>
<li>
<a href="https://www.mozilla.org/en-US/firefox/new/">
<img src="img/browsers/firefox.png" alt="">
<div>Firefox</div>
</a>
</li>
<li>
<a href="http://www.opera.com">
<img src="img/browsers/opera.png" alt="">
<div>Opera</div>
</a>
</li>
<li>
<a href="https://www.apple.com/safari/">
<img src="img/browsers/safari.png" alt="">
<div>Safari</div>
</a>
</li>
<li>
<a href="http://windows.microsoft.com/en-us/internet-explorer/download-ie">
<img src="img/browsers/ie.png" alt="">
<div>IE (New)</div>
</a>
</li>
</ul>
</div>
<p>Sorry for the inconvenience!</p>
</div>
<![endif]-->
<!-- Javascript Libraries -->
<!-- jQuery -->
<script src="vendors/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="vendors/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Placeholder for IE9 -->
<!--[if IE 9 ]>
<script src="vendors/bower_components/jquery-placeholder/jquery.placeholder.min.js"></script>
<![endif]-->
<!-- Site Functions & Actions -->
<script src="js/app.min.js"></script>
</body>
</html>
your using <form> tags without no action attribute (takes the url link which will handle the form) and method attributes(set this to POST, that is method="POST"). look through your code and correct this.
Each time you use and input field and what to get the data which the user inputted, enclosed it inside a form tags like this:
<form action="form processor url here" method="POST">
<!--input fields here or fields that you want the to submit data-->
<input type=text name=username >
<button name=login value=login >
</form>

Profile page that displays user information from MySQL database

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">

Categories