Javascript/Ajax/jQuery/SQL User Login - javascript

I have a system, where at one Computer/Monitor more than 1 user can be logged in.
First the user log in. This is already working. Then it shows the username which is logged in.
When an other user log in, it shows the second User also.
So far, so good.
But the whole page is reloaded. I want to reload only the part of the Website which has to be updated (the part where it is shown).
So my question is, how can I update only the Part of the website and which programmer speech I have to use.
The Users which are logged in are saved in a $_SESSION variable - not in the database.
Here is my Code:
in index.php (Session is started)
`
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="../main.css">
<link rel="stylesheet" href="../bootstrap/css/bootstrap.css">
<script type="text/javascript" src="../jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="container" id="content">
<div class="row" >
<div class="col-sm-6 col-sm-offset-3" id="formular">
<img src="../back.png" style="width: 10%;" id="back"/>
<b><h1 align="center">Login</h1></b>
<form action="php/login.php" method="post" style="text-align: center;">
<input type="text" class="form-control" style="width: 70%;margin: auto; margin-top: 2%;" id="username" name="username" placeholder="username" required/>
<input type="password" class="form-control" style="width: 70%;margin: auto; margin-top: 2%;" id="pwd" name="passwort" placeholder="passwort" required/>
<input type="submit" value="Login" style="padding-left: 10%; padding-right: 10%; margin-top: 2%;" class="btn btn-warning"/>
</form>
</div>
</div>
<div style="margin-top:1%" class="row">
<div class="col-sm-3 col-sm-offset-3 col-xs-6" id="teamRot">
<h1 align="center">Team Rot</h1>
<?php
echo $_SESSION['username1'];
echo "<br/>";
echo $_SESSION['username2'];
?>
</div>
<div class="col-sm-3 col-xs-6" id="teamBlau">
<h1 align="center">Team Blau</h1>
<?php
echo $_SESSION["username3"];
echo "<br/>";
echo $_SESSION["username4"];
?>
</div>
</div>
<div class="row">
<br/>
<div class="col-sm-2 col-sm-offset-5 col-xs-6 col-xs-offset-3 btn btn-warning" id="start" >
<a href="../Spiel/index.html" style="text-decoration: none; color: black" ><h1 align="center" >start</h1></a>
</div>
</div>
</div>
</body>
`
in login.php
<?php
session_start();
include "../../connector.php";
$username = $_POST['username'];
$passwort = $_POST['passwort'];
echo $_SESSION["zaehler"];
$stmt = $con->prepare("SELECT username FROM Spieler WHERE passwort=? AND username=?");
$stmt->bind_param("ss", $passwort, $username);
//mysqli_stmt_bind_param($stmt, "s", $passwort);
$stmt->execute();
$stmt->bind_result($ergebnis);
$stmt->fetch();
$stmt->close();
if($ergebnis == null)
{
echo "<script type=\"text/javascript\">";
echo "var checK = alert('Username oder Passwort falsch');
if (!checK)
{
history.go(-1); // go back since user clicked cancel
}";
echo "</script>";
}
else
{
$_SESSION["zaehler"]=$_SESSION["zaehler"] + 1;
if($_SESSION["zaehler"] == 1)
{ $_SESSION["username1"]= $ergebnis;}
elseif($_SESSION["zaehler"] == 2)
{ $_SESSION["username2"]= $ergebnis;}
elseif($_SESSION["zaehler"] == 3)
{ $_SESSION["username3"]= $ergebnis;}
elseif($_SESSION["zaehler"] == 4)
{ $_SESSION["username4"]= $ergebnis;}
elseif($_SESSION["zaehler"] == 5)
session_destroy();
header("Location:../index.php");
}

Related

Not being able to verify password SQL

Update: After someone suggested in comments it's working now. I am still not able to work the login/logout button that's in index.php file. When I log in it does verify the password, but does not show the logout button. It shows the error in index.php (I have commented out the line) it says undefined index name Any help is appreicated.
I have a signup and login form in my website. I am able to signup properly and I am storing the password as hashed. When I try to login it keep saying wrong password. I am assuming there might be something wrong with my code since the password I am typing is correct.
index.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "navigationbar.php";
require "loginpage.php";
?>
<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
<link href="stylee.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght#100&display=swap" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$user = $_SESSION['name'] ; //it says undefined index name
if (isset($user )) {
echo '<p>You are logged in</p>';
echo '<form action="logout.php" method="post">
<button type="submit" name="logout-submit">Logout</button>
</form>';
<link href="stylee.css" rel="stylesheet" />
<form action="logoutbackend.php" method="post">
<button type="submit" name="logout-submit" class="logout_button">Logout</button>
</form>';
} else {
echo '<p class="login-status">You are logged out!</p>';
echo '<div class="login-container">
<form action="./backend/loginbackend.php" method="post">
<div class="form-group row">
<div class="col-sm-10">
<h2>website</h2>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="email" class="form-control" name="email" placeholder="Email">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="password" class="form-control" name="password" placeholder="password">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary" name="login_submit">Log In</button>
</div>
</div>
</form>
<div class="form-group row">
<div class="col-sm-10">
<p>New to <span>ShowCo</span>?<a class="open-button" onclick="openForm()">Sign up</a> </p>
</div>
</div>
<div class="form-popup" id="myForm">
<form action="./backend/signupbackend.php" class="form-container" method="post">
<div class="form-group row">
<div class="col-sm-10" >
<h1>Sign up</h1>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="text" class="form-control" placeholder="Username" name="username" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="email"class="form-control" placeholder="Email address" name="mail" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="password" class="form-control" placeholder="Password" name="password" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="password" class="form-control" placeholder="Repeat password" name="repeatpassword" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<button type="submit" class="btn btn-primary" name="signup_submit">Sign up</button>
</div>
</div>
<button type="button" class="close" aria-label="Close" onclick="closeForm()"><span aria-hidden="true">×</span></button>
</form>
</div>
</div>
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
</script>
';
}
?>
</body>
</html>
<?php
require "footer.php";
?>
Signupbackend.php
<?php
if(isset($_POST["signup_submit"])) {
require "../database_files/database_for_signup.php";
require "../index.php";
$username = $_POST['username'];
$email = $_POST['mail'];
$password = $_POST['password'];
$repeatPassword = $_POST['repeatpassword'];
if (empty($username) || empty($email) || empty($password) || empty($repeatPassword)) {
header("Location: ../index.php?error=emptyfields&username=" .$username."&mail=" .$email);
exit();
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location: ../index.php?error=invalidmailusername");
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?error=invalidmail&username=".$username);
exit();
} else if (!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location: ../index.php?error=invalidusername&mail=".$email);
exit();
} else if($password != $repeatPassword) {
header("Location: ../index.php?error=passwordcheck&username=".$username."&mail=".$email);
exit();
} else {
$sql = "SELECT COUNT(username) AS num FROM signup_info WHERE username = :username";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['num'] > 0) {
die('Sorry, username already exists. Please try a different username');
}
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$sql = "INSERT INTO signup_info(username, email, password) VALUES (:username, :email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', $passwordHash);
$result = $stmt->execute();
if($result) {
echo "Registered!";
}
}
}
?>
Loginbackend.php
<?php
if(isset($_POST['login_submit'])) {
require "../database_files/database_for_signup.php";
$email = $_POST['email'];
$password = $_POST['password'];
if ((empty($username)) || (empty($password))) {
echo 'empty username/password';
die();
}
$sql = 'SELECT username, email, password FROM signup_info WHERE email = :email';
if ($stmt = $conn->prepare($sql)) {
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
if ($stmt->execute()) {
if($stmt->rowCount() == 1) {
if ($row = $stmt->fetch()) {
$hashed_password = $row['password'];
if(password_verify($password, $hashed_password)) {
session_start();
$_SESSION['email'] = $email;
$_SESSION['name'] = $row['username'];
echo "verfiied";
} else {
echo "wrong password"; }
}
}
}
}
}
?>
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: ./index.php");
Please help me why I am not able to verify the password? Also, I have been through similar questions on SO, but nothing helped. Any help is appreciated.

How to show selected image and its name?

I am studying and simply making an user registration form where there are several fields and the user has to upload its profile picture. I use php in order to validate the data before submitting.
After hitting the submit button it validates the data and refreshes the page due to which the filled data is gone. So we use ex. value="<?php echo $name; ?>" in the input value in order to preserve the data inserted by the user. It is possible with the simple input types such as text and others but how do we preserve the data of the image and show it in the image container and show the name of the selected image in the input type file.
<!DOCTYPE html>
<!-- form -->
<?php
$nameError = $genderError = $emailError = $mobileError = $imageError = "";
$name = $gender = $email = $mobile = $image = "";
$imagePath = $_FILES['image']['name'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameError = "Please provide Name";
} else {
$name = validateInput($_POST["name"]);
}
if (empty($_POST["gender"])) {
$genderError = "Please select Gender";
} else {
$gender = validateInput($_POST["gender"]);
}
if (empty($_POST["email"])) {
$emailError = "Please provide Email ID";
} else {
$email = validateInput($_POST["email"]);
}
if (empty($_POST["mobile"])) {
$mobileError = "Please provide Mobile Number";
} else {
$mobile = validateInput($_POST["mobile"]);
}
if (empty($_POST["image"])) {
$imageError = "Please provide Image";
} else {
$image = validateInput($_POST["image"]);
}
}
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html lang="en" dir="ltr">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/master.css">
<!-- style -->
<style media="screen">
.center {
text-align: center;
}
.required {
color: #ff0000;
}
form {
margin-bottom: 50px;
}
</style>
</head>
<body>
<div class="center container-fluid" style="margin: 50px;">
<h1 class="display-1">User Registration</h1>
</div>
<div class="container">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<!-- name -->
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Name</span>
</div>
<input type="text" class="form-control" name="name" value="<?php echo $name; ?>">
</div>
<span class="required"><?php echo $nameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Gender</span>
</div>
<select class="form-control" name="gender">
<option <?php if (isset($gender) && $gender == "") echo "selected" ?> value="">Select your gender</option>
<option <?php if (isset($gender) && $gender == "1") echo "selected" ?> value="1">Male</option>
<option <?php if (isset($gender) && $gender == "0") echo "selected" ?> value="0">Female</option>
</select>
</div>
<span class="required"><?php echo $genderError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Email</span>
</div>
<input class="form-control" type="email" name="email" value="<?php echo $email; ?>">
</div>
<span class="required"><?php echo $emailError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Mobile</span>
</div>
<input class="form-control" minlength="10" maxlength="10" type="tel" name="mobile" value="<?php echo $mobile; ?>">
</div>
<span class="required"><?php echo $mobileError; ?></span>
</div>
<!-- image container -->
<div class="form-group" id="image_container" style="display: none;">
<img src="#" id="selected_image" width="300" height="175">
</div>
<?php echo $imagePath; ?>
<?php
if (isset($imagePath) && $imagePath != "") {
echo
"<script type='text/javascript'>
document.getElementById('image_container').style.display = 'block';
document.getElementById('selected_image').src = '" . $imagePath ."';
</script>";
}
?>
<!-- image -->
<div class="form-group">
<input class="form-control" type="file" name="image" onchange="readURL(this)">
<span class="required"><?php echo $imageError; ?></span>
</div>
<!-- submit -->
<center>
<input type="submit" class="btn btn-info">
<center>
</form>
</div>
</body>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#selected_image').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
document.getElementById("image_container").style.display = "block";
}
}
</script>
</html>
Please have a look and help and suggest me.

How to append a row to a table created in pdf using tcpdf by using javaScript or jquery?

I have a form in which there are two fields: amount input and submit button. On submitting this form I want the data to be stored in database and should be displayed in pdf using tcpdf. Everytime i add an amount it should be appended to a table in a row inside pdf. How to do this?? Please help me with this.
Following is the form which submits the amount:
<div class="form-group">
<label class="col-sm-3 control-label" for="amount">Amount</label>
<div class="col-sm-9">
<input type="number" class="form-control" name="amount"
id="amount" placeholder="Amount">
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button type="submit" class="btn btn-success" id="pay-now" name="pay-
now">Pay Now</button>
</div>
</div>
Following is the php code using tcpdf:
if(isset($_POST["pdf"]))
{
require_once('tcpdf/tcpdf.php');
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8',
false);
$obj_pdf->SetCreator(PDF_CREATOR);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '',
PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '',
PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, '4', PDF_MARGIN_RIGHT);
$obj_pdf->setPrintHeader(false);
$obj_pdf->setPrintFooter(false);
$obj_pdf->SetAutoPageBreak(TRUE, 10);
$obj_pdf->SetFont('helvetica', '', 12);
$obj_pdf->AddPage();
$sql = "SELECT * FROM donors WHERE user_name='$username'";
$result = mysqli_query($conn, $sql);
$html = '';
$html .= '
<!doctype html>
<html lang="en">
<head>
<style>
.text-center{
text-align: center;
}
.img-fluid{
width: 200px;
height: 41px;
}
.title{
text-decoration: underline;
}
.text-left{
text-align: left;
}
</style>
</head>
<body>
<div >
<div class="text-center">
<div >
<img src="img/logo.png" class="img-fluid">
</div>
<div class="title">
<h1>Donation Report</h1>
</div>
<div >
<h3 >';
$html .= "Date : " . date("m-d-Y");
$html .= '</h3>
</div>
<div class="text-left">
<h4>Hello ';
$html .= $_SESSION['u_user_name'];
$html .= ',</h4>
<p>Thanks a lot for donating and supporting us. Please find your
details below for tax filing:</p>
</div>
<div>
<table border="1" cellspacing="0" cellpadding="5" id="box">
<tr>
<td>Date</td>
<td>Amount</td>
</tr><tr><td>';
$html .= date("m-d-Y");
$html .= '</td><td>';
while($row = mysqli_fetch_assoc($result)){
$html .= $row["total_donation_amount"];
}
$html .= '</td></tr></table>
</div>
<div class=" text-left">
<h4>Thanks and Regards,</h4>
<h4>Detroit Pheonix Center</h4>
<h4>Detroit, Mi</h4>
</div>
</div>
</div>
</body>
</html>';
$obj_pdf->writeHTML($html);
$obj_pdf->Output('donor_report.pdf', 'D');}
Here when i submit the form, i want the date of payment and amount should be displayed in the table row of pdf and each time i do this the row should be appended to the pdf. pdf is printed using pdf button which is in other code which i have not mentioned here.

Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart

Having difficulty identifying what is throwing the error. Have removed all white space. Using CodeAnywhere as my IDE as it is a requirement for me. Any help would be appreciated.
Full error:
Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart.php:134) in /home/cabox/workspace/Project/ShoppingCart.php on line 169
Code:
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "lab"); //connect to the db
if(isset($_POST["add_to_cart"])) //if the add to cart value is set
{
if(isset($_SESSION["shopping_cart"])) //if the shopping cart session is set
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
//if there are values in your shopping cart loop through and display them
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo '<script>alert("Item Already Added")</script>';
//restriction on design - can only add one instance of each product, delete if you want to add more
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
//when you select 'Remove', delete the values based on id. Alert box will show on completition
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item has been removed from Shopping Cart")</script>';
echo '<script>window.location="ShoppingCart.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<!-- AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.-->
<link rel="stylesheet" type="text/css" href="thePerfectPair.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</head>
<body>
<nav class="navigationBar">
<!--Establishing the top left hand side of the Navigation Bar-->
<div class="leftTopNavBar">
€ EUR |
<!--The following produces a pop up sign up form that is validated through javascript functions in the following code.
I implemented this pop up form to create a different design element as opposed to just referring users to another page.
All design element are assigned in the css file and it involved calling many different classes in order not to conflict
with other forms and input boxes contained in the website-->
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;" class="SignUpBtn0">SIGN UP |</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content" action="/action_page.php">
<div class="container1">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account with Perfect Pair!</p>
<hr>
<b>Email</b>
<input type="text" placeholder="Enter Email" name="email" required>
<b>Password</b>
<input type="password" placeholder="Enter Password" name="psw" required>
<b>Repeat Password</b>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
SAVED ITEMS
</div>
<!--Establishing the right side of the navBar-->
<div class="rightTopNavBar">
<input type="search" placeholder="Search..." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
LOGIN | CART
<i class="fa fa-shopping-cart" style="font-size:20px"></i>
</div>
<!--Establishing the middle of the navBar-->
<div class="middleTopNavBar">
<img src="Images/perfectPairLogo.png" class="logoHeader" alt="logo" width="100" height="100">
</div>
<!--Establishing bottom navBar-->
<div class="bottomNavBar">
<i class="fa fa-home" style="font-size:36px"> </i>
 HEELS 
 SANDALS 
 BOOTS 
 TRAINERS 
 FLATS 
 SHOPPING CART </div></nav>
<div class="container">
<br><?php $query="SELECT*FROM tbl_product1 ORDER BY id ASC"; $result=mysqli_query($connect, $query); if(mysqli_num_rows($result)>0){while($row=mysqli_fetch_array($result)){?><div class="col-md-4">
<form method="post" class="phpForm" action="ShoppingCart.php?action=add&id=<?php echo $row["id"];?>" >
<div class="formStyleDiv" style=" background-color:#f1f1f1; border-radius:1px; padding:16px; width:25%;" align="center">
<img src="Images/<?php echo $row["image"];?>" class="img-responsive" style="height: 200px;" />
<h4 class="text-info"><?php echo $row["name"];?></h4><br />
<h4 class="text-danger">€<?php echo $row["price"];?></h4>
<input type="text" name="quantity" value="1" class="form-control" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"];?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"];?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="submitBtn" class="btn btn-success" value="Add to Cart" /></div>
</form>
</div><?php
}
}
?><div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive" >
<table>
<tr>
<th width="40%" align="left">Item Name</th>
<th width="10%" align="left">Quantity</th>
<th width="20%" align="left">Price</th>
<th width="15%" align="left">Total</th>
<th width="5%" align="left">Action</th>
</tr><?php if(!empty($_SESSION["shopping_cart"])) { $total = 0; foreach($_SESSION["shopping_cart"] as $keys => $values){?><tr>
<td><?php echo $values["item_name"];?></td>
<td><?php echo $values["item_quantity"];?></td>
<td>€<?php echo $values["item_price"];?></td>
<td>€<?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
<td><span class="text-danger">Remove</span></td>
</tr><?php $total = $total + ($values["item_quantity"] * $values["item_price"]);}?><tr>
<td colspan="3" align="right">Total</td>
<td align="right">€<?php echo number_format($total, 2); ?></td>
<td></td>
</tr><?php $cookie_name="Total"; setcookie($cookie_name, $total, time()+(86400*30),"/");}?></table></div>
<input type="button" class="submitFormBtn" name="submit" value= "Submit" onclick="window.open ('success.php','_self',false)" /><br />
</div>
</div>
<br />
</body>
</html>

html form,db submission,empty data on refresh or back

I have a from submitting data to db,and after entering in to db thank you message comes,everything is in same page.the problem is wheni refresh or go back the same data or empty data is entered in to db. Please help`
<?php
$myServer = "localhost";
$myUser = "root";
$myPass = "";
$myDB = "sample";
$name=$_POST['fname'];
$mobile=$_POST['mobile'];
$email=$_POST['email'];
//connection to the database
$dbhandle = mysql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mysql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//echo "$myDB";
//Insert data into db
mysql_query("INSERT INTO reg(name,mobile,email) values ('$name','$mobile','$email')");
/* echo "$name";
echo "$mobile";
echo "$email"; */
//header("location:thank.html");
?>
<!doctype html>
<html>
<head>
<title>Basic form with validation</title>
<link rel="stylesheet" href="style/style.css" type="text/css" media="all"/>
</head>
<body>
<div style="width:300px; background:#19a3d1;margin:0 auto;height:200px;">
<?php
if(empty($_POST))
{
?>
<form name="myform" id="frm1" action="index.php" method="post" style="margin:0 auto;"onsubmit="return(validate());">
<h1 style="text-align:center">Form</h1>
<div style="display: table; margin:0 auto;">
<div style="display: table-row;">
<div style="display: table-cell;padding:5px;">
<label>Name</label>
</div>
<div style="display: table-cell;">
<input type="text" name="fname" id="fname" placeholder="Name" />
</div>
</div>
<div style="display: table-row;">
<div style="display: table-cell;padding:5px;">
<label>Mobile</label>
</div>
<div>
<input type="text" name="mobile" id="mobile" placeholder="Mobile" />
</div>
</div>
<div style="display: table-row;">
<div style="display: table-cell;padding:5px;">
<label>Email</label>
</div>
<div>
<input type="text" name="email" id="email" placeholder="Email" />
</div>
</div>
<div style="display: table-row;">
<div style="display: table-cell;padding:5px;" ></div>
<div style="display: table-cell;padding:5px;"><input type="submit" value="Submit"></div>
</div>
</div>
</form>
<?php
}
else{
?>
<div id="thank" >
<span style="color:#ff0000;padding:30px;text-align:center;display:block;">Thank you!!</span>
</div>
<?php
}
?>
</div>
<script src="js/main.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</body>
</html>`
Give name of your submit button.
Like
<input type="submit" value="Submit" name="btnSubmit">
And Write PHP Code like this :
<?php
......
......
if(isset($_POST['btnSubmit']))
{
Your code....
}
?>
Or
You can use ajax to submit the form data.
http://www.formget.com/submit-form-using-ajax-php-and-jquery/

Categories

Resources