currently I am doing multiple page form (page 1 and page 2). I save the details in page 1 using SESSION and insert successfully to database. I also successfully retrieve the data from database and display on page (activityLog.php).
However, I face problem when I want to edit/update the form.The value in the form wasn't update as well as the database. Please help.Thanks.
Below is my display cause page and edit form (editIndividual.php).
activityLog.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>My Activity Log</title>
<?php
session_start();
include 'header.php';
?>
<div id="content">
<div class="section">
<h4 align="center" style="font-size:28px;">My Activity Log</h4>
<div>
Basic Setting
Change Password
<a class="selected" href="activityLog.php">My Activity Log</a>
</div>
<label style="font-size:19px;color:#333;"<strong>Manage your cause below.</strong>
<div class="figure">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class="register">
<div class="first" >
<?php
include 'dbconn.php';
if(isset($_SESSION['email'])){
$query="SELECT * from cause join user_info on cause.userID=user_info.userID where email='{$_SESSION['email']}'";
$result=mysqli_query($conn, $query);
while ($row=mysqli_fetch_array($result)){
$causeID = $row['causeID'];
$title = $row['title'];
$category = $row['category'];
$donateType = $row['donateType'];
$goal = $row['goal'];
$description = $row['description'];
$createDate = $row['createDate'];
$image = $row['image'];
echo "<a href='editIndividual.php?u=$causeID'>".$title."</a><br>";
echo "<img height='80' width='100' src='upload/".$image."'><br>";
}
}
?>
<fieldset>
</fieldset>
</div>
</form><!--end form-->
</div>
</div>
</div>
<?php include 'footer.php';?> <!--include footer.php-->
</body>
</html>
editIndividual.php
<html>
<head>
<meta charset="UTF-8" />
<!--include header-->
<?php
session_start();
include 'dbconn.php';
include 'header.php';
if(!isset($_SESSION['email'])){
echo "Please login before proceed!";
header("location:login.php");
}
else{
if(isset($_GET['u'])){
$causeID = $_GET['u'];
$query="SELECT * from cause where causeID=$causeID ";
$result=mysqli_query($conn, $query);
while ($row=mysqli_fetch_array($result)){
$causeID = $row['causeID'];
$title = $row['title'];
$category = $row['category'];
$donateType = $row['donateType'];
$goal = $row['goal'];
$description = $row['description'];
$createDate = $row['createDate'];
$image = $row['image'];
}
//update title
$title = $_SESSION['title'];
$upTitle = "UPDATE cause set title='$title' where causeID='$causeID'";
$upTitleResult = mysqli_query($conn,$upTitle);
//update category
$category = $_SESSION['category'];
$upCategory = "UPDATE cause set category='$category' where causeID='$causeID'";
$upCategoryResult = mysqli_query($conn,$upCategory);
//update donate type
$donateType = $_SESSION['donateType'];
$upDonateType = "UPDATE cause set donateType='$donateType' where causeID='$causeID'";
$upDonateTypeResult = mysqli_query($conn,$upDonateType);
//update goal
$goal = $_SESSION['goal'];
$upGoal = "UPDATE cause set goal='$goal' where causeID='$causeID'";
$upGoalResult = mysqli_query($conn,$upGoal);
//update description
$description = $_POST['description'];
$upDes = "UPDATE cause set description='$description' where causeID='$causeID'";
$upDesResult = mysqli_query($conn,$upDes);
//update image
$image = $_FILES['imageToUpload']['name'];
$upImage = "UPDATE cause set image='$image' where causeID='$causeID'";
$upImageResult = mysqli_query($conn,$upImage);
}
}
?>
<!--Change choose file button default name-->
<script>
function HandleBrowseClick()
{
var fileinput = document.getElementById("imageToUpload");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("imageToUpload");
fileinput.value;
}
</script>
<div id="content">
<div>
<form action="activityLog.php" id="editInd_form" name="editInd_form" class= "register" method="post">
<div class="first">
<fieldset>
<label for="title"><strong>Cause Title: </strong></label><br>
<input type="text" id="title" name="title" class="inputtext" value="<?php echo $title?>"/><br>
<label for="category" ><strong><span class="error-message" style="color:red">*</span>Category:</strong></label><br>
<select id="category" name="category" onchange="document.getElementById('editInd_form').submit()">
<?php
$categoryArray=array("Select a category", "Animal Welfare", "Children", "Education", "Environment", "Health", "OKU", "Refugees", "Senior Citizen", "Community", "Women Welfare", "Youth");
for ($i=0; $i<count($categoryArray); $i++){
if ($i == $category){
echo "<option value='".$i."' selected>".$categoryArray[$i]."</option>";
}
else{
echo "<option value='".$i."'>".$categoryArray[$i]."</option>";
}
}
?>
</select><br>
<label for="donateType"><strong><span class="error-message" style="color:red;">*</span>Type of Donation:</strong></label><br>
<select id="donateType" name="donateType" onchange="document.getElementById('editInd_form').submit()" >
<?php
$donateTypeArray=array("Please Select","Fundraising","Books","Clothing","Electric product", "Food","Water","Other");
for ($j=0; $j<count($donateTypeArray); $j++){
if ($j == $donateType){
echo "<option value='".$j."' selected>".$donateTypeArray[$j]."</option>";
}
else{
echo "<option value='".$j."'>".$donateTypeArray[$j]."</option>";
}
}
?>
</select><br>
<label for="goal"><strong><span class="error-message" style="color:red">*</span>Please state your goal:</strong></label><br>
<input type="text" id="goal" name="goal" class="inputtext" value="<?php echo $goal?>" placeholder="enter an amount(RM) for fundraising, uniform, 1.5L mineral water, ..."><br>
</fieldset></div>
<div><fieldset>
<label for="description"><strong>Tell us your story: </strong></label><br>
<textarea name="description" style="width:350px;height:150px;"><?php echo $description?>
</textarea><br>
<!-- <img src="images/image-icon.png" class="image-icon" height="150" width="150"> <img src="images/video-icon.png" height="150" width="150">-->
<label for="imageToUpload"><strong>Upload Your Photo:</strong></label><br>
<input type="file" name="imageToUpload" id="imageToUpload" style="display:none;" onChange="Handlechange();">
<input type="button" value="Change image" id="fakeBrowse" onclick="HandleBrowseClick();"/>
<?php include 'upload1.php';?>
<input type="submit" name="submit" id="save" value=""><br>
</fieldset>
</div>
</form>
</table>
</div>
</div> <!--content end-->
<!--include footer-->
<?php include 'footer.php';?>
</body>
</html>
for your reference, this is my create form (2 pages form)
createIndividual.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!--include header-->
<?php
session_start();
include 'dbconn.php';
if(!isset($_SESSION['email'])){
echo "Please login before proceed!";
header("location:login.php");
}
include 'header.php';
?>
<div id="content">
<div>
<h3 align="center"> Create your own cause</h3>
<h4><strong> Step 1: Title, Category, Goal</strong></h4>
<form action="createIndividual2.php" id="createInd_form" class= "register" method="post">
<div class="form">
<fieldset>
<label for="title"><strong>Cause Title: </strong></label><br>
<input type="text" id="title" name="title" class="inputtext"/><br>
<label for="category" ><strong><span class="error-message" style="color:red">*</span>Category:</strong></label><br>
<select id="category" name="category">
<option value="0"> Select a category</option>
<option value="1"> Animal Welfare</option>
<option value="2"> Children</option>
<option value="3"> Education </option>
<option value="4"> Environment</option>
<option value="5"> Health</option>
<option value="6"> OKU</option>
<option value="7"> Refugees</option>
<option value="8"> Senior Citizen</option>
<option value="9"> Community</option>
<option value="10"> Women Welfare</option>
<option value="11"> Youth</option>
</select><br>
<label for="donateType"><strong><span class="error-message" style="color:red;">*</span>Type of Donation:</strong></label><br>
<select id="donateType" name="donateType">
<option value="0">Please Select</option>
<option value="1">Fundraising</option>
<option value="2">Books</option>
<option value="3">Clothing</option>
<option value="4">Electric product</option>
<option value="5">Food</option>
<option value="6">Water</option>
<option value="7">Other</option>
</select><br>
<label for="goal"><strong><span class="error-message" style="color:red">*</span>Please state your goal:</strong></label><br>
<input type="text" id="goal" name="goal" class="inputtext" placeholder="enter an amount(RM) for fundraising, uniform, 1.5L mineral water, ..."><br>
<input type="submit" name="submit" id="next" value=""><br>
</fieldset>
</div>
</form>
</table>
</div>
</div> <!--content end-->
<!--include footer-->
<?php include 'footer.php';?>
</body>
</html>
createIndividual2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!--include header-->
<?php
session_start();
$_SESSION['title'] = $_POST['title'];
$_SESSION['category'] = $_POST['category'];
$_SESSION['donateType'] = $_POST['donateType'];
$_SESSION['goal'] = $_POST['goal'];
include 'header.php';
?>
<div id="content">
<div>
<h3 align="center"> Create your own cause</h3>
<h4><strong> Step 2: Tell us your story</strong></h4>
<form action="checkCause.php" id="createIndividual" class= "register" method="post" enctype="multipart/form-data">
<div class="form">
<fieldset>
<label for="title"><strong>Tell us your story: </strong></label><br>
<textarea name="description" style="width:500px;height:150px;">
</textarea><br>
<!-- <img src="images/image-icon.png" class="image-icon" height="150" width="150"> <img src="images/video-icon.png" height="150" width="150">-->
<label for="imageToUpload"><strong>Upload Your Photo:</strong></label><br>
<input type="file" name="imageToUpload" id="imageToUpload">
<input type="submit" name="upload" id="submit" value=""><br>
<button onclick="goBack()" id="back"></button>
<script>
function goBack() {
window.history.back();
}
</script>
<?php include 'upload1.php';?>
</fieldset>
</div>
</form>
</table>
</div>
</div> <!--content end-->
<?php include 'footer.php';?> <!--include footer.php-->
</body>
</html>
In editIndividual.php you have a error. You first get data from MySQL and after that you setup data from sessions. But where you check if new data exist and return old if not exists?
Look my integration in your code:
<html>
<head>
<meta charset="UTF-8" />
<!--include header-->
<?php
session_start();
include 'dbconn.php';
include 'header.php';
if(!isset($_SESSION['email'])){
echo "Please login before proceed!";
header("location:login.php");
}
else{
if(isset($_GET['u'])){
$causeID = $_GET['u'];
$query="SELECT * from cause where causeID=$causeID ";
$result=mysqli_query($conn, $query);
while ($row=mysqli_fetch_array($result)){
$causeID = $row['causeID'];
$title = $row['title'];
$category = $row['category'];
$donateType = $row['donateType'];
$goal = $row['goal'];
$description = $row['description'];
$createDate = $row['createDate'];
$image = $row['image'];
}
//update title
$title = (isset($_SESSION['title'])&&!empty($_SESSION['title'])?$_SESSION['title']:$title);
$upTitle = "UPDATE cause set title='$title' where causeID='$causeID'";
$upTitleResult = mysqli_query($conn,$upTitle);
//update category
$category = (isset($_SESSION['category'])&&!empty($_SESSION['category'])?$_SESSION['category']:$category);
$upCategory = "UPDATE cause set category='$category' where causeID='$causeID'";
$upCategoryResult = mysqli_query($conn,$upCategory);
//update donate type
$donateType = (isset($_SESSION['donateType'])&&!empty($_SESSION['donateType'])?$_SESSION['donateType']:$donateType);
$upDonateType = "UPDATE cause set donateType='$donateType' where causeID='$causeID'";
$upDonateTypeResult = mysqli_query($conn,$upDonateType);
//update goal
$goal = (isset($_SESSION['goal'])&&!empty($_SESSION['goal'])?$_SESSION['goal']:$goal);
$upGoal = "UPDATE cause set goal='$goal' where causeID='$causeID'";
$upGoalResult = mysqli_query($conn,$upGoal);
//update description
$description = (isset($_POST['description'])&&!empty($_POST['description'])?$_POST['description']:$description);
$upDes = "UPDATE cause set description='$description' where causeID='$causeID'";
$upDesResult = mysqli_query($conn,$upDes);
//update image
$image = (isset($_FILES['imageToUpload']['name']) && !empty($_FILES['imageToUpload']['name'])?$_FILES['imageToUpload']['name']:$image);
$upImage = "UPDATE cause set image='$image' where causeID='$causeID'";
$upImageResult = mysqli_query($conn,$upImage);
}
}
?>
<!--Change choose file button default name-->
<script>
function HandleBrowseClick()
{
var fileinput = document.getElementById("imageToUpload");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("imageToUpload");
fileinput.value;
}
</script>
<div id="content">
<div>
<form action="activityLog.php" id="editInd_form" name="editInd_form" class= "register" method="post">
<div class="first">
<fieldset>
<label for="title"><strong>Cause Title: </strong></label><br>
<input type="text" id="title" name="title" class="inputtext" value="<?php echo $title?>"/><br>
<label for="category" ><strong><span class="error-message" style="color:red">*</span>Category:</strong></label><br>
<select id="category" name="category" onchange="document.getElementById('editInd_form').submit()">
<?php
$categoryArray=array("Select a category", "Animal Welfare", "Children", "Education", "Environment", "Health", "OKU", "Refugees", "Senior Citizen", "Community", "Women Welfare", "Youth");
for ($i=0; $i<count($categoryArray); $i++){
if ($i == $category){
echo "<option value='".$i."' selected>".$categoryArray[$i]."</option>";
}
else{
echo "<option value='".$i."'>".$categoryArray[$i]."</option>";
}
}
?>
</select><br>
<label for="donateType"><strong><span class="error-message" style="color:red;">*</span>Type of Donation:</strong></label><br>
<select id="donateType" name="donateType" onchange="document.getElementById('editInd_form').submit()" >
<?php
$donateTypeArray=array("Please Select","Fundraising","Books","Clothing","Electric product", "Food","Water","Other");
for ($j=0; $j<count($donateTypeArray); $j++){
if ($j == $donateType){
echo "<option value='".$j."' selected>".$donateTypeArray[$j]."</option>";
}
else{
echo "<option value='".$j."'>".$donateTypeArray[$j]."</option>";
}
}
?>
</select><br>
<label for="goal"><strong><span class="error-message" style="color:red">*</span>Please state your goal:</strong></label><br>
<input type="text" id="goal" name="goal" class="inputtext" value="<?php echo $goal?>" placeholder="enter an amount(RM) for fundraising, uniform, 1.5L mineral water, ..."><br>
</fieldset></div>
<div><fieldset>
<label for="description"><strong>Tell us your story: </strong></label><br>
<textarea name="description" style="width:350px;height:150px;"><?php echo $description?>
</textarea><br>
<!-- <img src="images/image-icon.png" class="image-icon" height="150" width="150"> <img src="images/video-icon.png" height="150" width="150">-->
<label for="imageToUpload"><strong>Upload Your Photo:</strong></label><br>
<input type="file" name="imageToUpload" id="imageToUpload" style="display:none;" onChange="Handlechange();">
<input type="button" value="Change image" id="fakeBrowse" onclick="HandleBrowseClick();"/>
<?php include 'upload1.php';?>
<input type="submit" name="submit" id="save" value=""><br>
</fieldset>
</div>
</form>
</table>
</div>
</div> <!--content end-->
<!--include footer-->
<?php include 'footer.php';?>
</body>
</html>
Related
I'm updating my post with an image field. Every thing is going fine, but i lose the path of the image, son if i leave the field empty the image path is null.
I have been trying different ways of including the old path to the field image. Those are the lines that have the old path and the new path.
<input type="file" name="image" value="<?php echo $row['image']; ?>">
<input type="hidden" name="old_image" value="<?php echo $row['image']; ?>" >
I tried also with <input type="file" name="image" value="<?php echo $image; ?>"> but it doesn't work.
Any suggestion?
Thanks in advance!
:)
This is my code:
<?php
require 'database.php';
$db = mysqli_connect("", "", "", "");
$id=$_GET["id"];
$title='';
$image='';
$image_text='';
$category='';
$result = mysqli_query($db, "SELECT * FROM `images` WHERE `id` = $id ");
while ($row = mysqli_fetch_array($result))
{
$title=$row['title'];
$image=$row['image'];
$papayos = $row['papayos'];
$cantidad = $row['cantidad'];
$image_text=nl2br($row['image_text']);
$category=$row['category'];
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Modificar. Lapapaya.org Educación y colaboración </title>
<meta name="keywords" content="colaboracion, economía del bien común, emprendimiento"/>
<meta name="description" content="Plataforma para desarrollo de proyectos productivos con bonos de intercambio"/>
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.8.0/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<section class="section has-background-white">
<div class="container">
<div class="columns is-centered">
<img class="logo-intro" src="images/logo.png" alt="Logo">
<br>
</div>
</div>
</section>
<form method="POST" action='' enctype="multipart/form-data">
<div class="container">
<h1>Título del artículo</h1>
<br>
<div class="field">
<div class="control">
<input class="input is-warning is-fullwidth" type="text" name="title" value="<?php echo $title; ?>" placeholder="Título">
</div>
<br>
<br>
<div>
<div class="notification"> <h1>Imagen</h1>
<input type="hidden" name="size" value="1000000">
<div class="field">
<div class="control">
<input type="file" name="image" value="<?php echo $row['image']; ?>">
<input type="hidden" name="old_image" value="<?php echo $row['image']; ?>" >
</div>
</div>
<div>
<h1>Descripción</h1>
<textarea class="textarea" name="image_text" rows="8" cols="80"><?php echo $image_text; ?></textarea>
<br>
<h1>Categoría</h1>
<div class=" select is-warning is-fullwidth">
<select type="text" class="" name="category" value="<?php echo $category; ?>">
<option value="1 ">Productos agrícolas</option>
<option value="2 ">Servicio</option>
<option value="3 ">Artesanía</option>
<option value="4 ">Arte</option>
<option value="5">Diseño Industrial</option>
<option value="6 ">Ciudad</option>
<option value="7 ">Economía</option>
<option value="8 ">Emprendimiento</option>
<option value="9 ">Programación</option>
<option value="10 ">Reflexión</option>
<option value="11">Río</option>
<option value="12 ">Seguridad alimentaria</option>
<option value="13 ">Vivienda</option>
</select>
</div>
<h1>Precio</h1>
<br>
<div class="field">
<div class="control">
<input class="input is-warning" type="number" name="papayos" value="<?php echo $papayos; ?>" placeholder="Papayos">
</div>
<br>
<h1>Cantidad</h1>
<br>
<div class="field">
<div class="control">
<input class="input is-warning" type="number" name="cantidad" value="<?php echo $cantidad; ?>" placeholder="Cantidad">
</div>
<br>
<br>
<div>
<button class="button is-outlined is-medium is-fullwidth" type="update" name="update">Modificar</button>
</div>
</div>
</form>
</body>
</html>
<?php
$server = '';
$username = '';
$password = '';
$database = '';
if (isset($_POST['update'])) {
$title=$_POST['title'];
$image_text=nl2br($_POST['image_text']);
$category=$_POST['category'];
$papayos =$_POST['papayos'];
$cantidad =$_POST['cantidad'];
$total = $papayos * $cantidad;
$old_image = $_POST['old_image'];
if(isset($_FILES['image']['name']) && ($_FILES['image']['name']!="")) {
$size=$_FILES['image']['size'];
$temp=$_FILES['image']['tmp_name'];
$type=$_FILES['image']['type'];
$image_name=$_FILES['image']['name'];
unlink("images/$old_image");
move_uploaded_file($temp, "images/$image_name");
}else {
$image_name=$old_image;
}
$update=mysqli_query($db, "UPDATE images SET title = '$title', image = '$image_name', image_text = '$image_text', category = '$category', papayos = '$papayos', cantidad = '$cantidad', total = '$total' WHERE id = $id");
if ($update) {
echo "<script>alert('Datos actualizados exitosamente')</script>";
echo "<script>window.open('index.php', '_self')</script>";
}
else {
echo "<script>alert('Inserción fallida')</script>";
}
} ?>
I fixed adding this above the imput file:
<img src="images/<?php echo $image; ?>">
:)
I want to block access to a PHP page.
I'm doing that with this way: If you been logged in, PHP check if exist a cookie, and doing echo the HTML, else it's redirecting you to login page.
Here is the code but when I'm trying to set value attribute equal to a PHP variable, I'm getting back the php code ex.""
The PHP code inside the selection tag, isn't working either!
<?php
if(isset($_COOKIE['User_Email_Cookie'])) {
session_start();
$name =$_SESSION['User_FullName'];
$phone =$_SESSION['User_Phone'];
echo '<!DOCTYPE html>
<html>
<body>
<h1 class="Title">Reserve a table now!</h1>
<center>
<form action="reservation2.php" method="post">
<div class="App">
<div class="User">
<h2 style="text-align:left;"> Contact:</h2>
<input type="text" id="Name" placeholder="Full Name" value="<?php echo $name ?>" required>
<input type="tel" id="Phone" placeholder="Phone" value="<?php echo $phone ?>" required>
</div>
<div class="DatePeople">
<h2> Choose the Date:</h2>
<input type="date" id="Date" name="TableDate">
<select name="Time" class="time">
<option>19:00</option>
<option>19:30</option>
<option>20:00</option>
<option>20:30</option>
<option>21:00 </option>
<option>21:30</option>
<option>22:00</option>
</select>
<h2 style="margin-top:0px;">Choose Table, People: <a target="_blank" href="media/diagram.png"><img src="media/info.png" width="23px"></a></h2>
<select name="TableNum" class="table">
<?php
include \'connectDb.php\'; #Eisagwgi stoixeiwn gia syndesi me ti vasi
$result=mysqli_query($con,"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE
TABLE_NAME = \'available\' AND COLUMN_NAME NOT IN (\'Date\', \'Time\')");
while($row = mysqli_fetch_array($result)) {
echo \'<option>\'.$row[0].\'</option>\';
}
?>
</select>
<input type="number" id="seats" name="People" min="2" max="8" value="4" >
</div>
</div>
<div>
<input type="submit" name="Submit" value="Reserve">
<a class="button" href="logout.php">Log out</a>
</div> </center>
</form>
else {
header("location: reservation.php");
}
The issue is that you echo the html, and inside that echo you combine "inner" php tags (value="<?php echo $name ?>" instead of value="' . $name . '" for example).
Change:
echo '<!DOCTYPE html>
To:
?><!DOCTYPE html>
And at the end, where you have:
</form>
Replace it with
</form></body></html><?php
The above code allows you combine html markup, by closing the php tags in the correct place, without you having to echo it with php.
Read the documentation for more details.
Please try this code
<?php
if(isset($_COOKIE['User_Email_Cookie'])) {
session_start();
$name =$_SESSION['User_FullName'];
$phone =$_SESSION['User_Phone'];
?>
<!DOCTYPE html>
<html>
<body>
<h1 class="Title">Reserve a table now!</h1>
<center>
<form action="reservation2.php" method="post">
<div class="App">
<div class="User">
<h2 style="text-align:left;"> Contact:</h2>
<input type="text" id="Name" placeholder="Full Name" value="<?php echo $name ?>" required>
<input type="tel" id="Phone" placeholder="Phone" value="<?php echo $phone ?>" required>
</div>
<div class="DatePeople">
<h2> Choose the Date:</h2>
<input type="date" id="Date" name="TableDate">
<select name="Time" class="time">
<option>19:00</option>
<option>19:30</option>
<option>20:00</option>
<option>20:30</option>
<option>21:00 </option>
<option>21:30</option>
<option>22:00</option>
</select>
<h2 style="margin-top:0px;">Choose Table, People: <a target="_blank" href="media/diagram.png"><img src="media/info.png" width="23px"></a></h2>
<select name="TableNum" class="table">
<?php
include \'connectDb.php\'; #Eisagwgi stoixeiwn gia syndesi me ti vasi
$result=mysqli_query($con,"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE
TABLE_NAME = \'available\' AND COLUMN_NAME NOT IN (\'Date\', \'Time\')");
while($row = mysqli_fetch_array($result)) {
echo \'<option>\'.$row[0].\'</option>\';
}
?>
</select>
<input type="number" id="seats" name="People" min="2" max="8" value="4" >
</div>
</div>
<div>
<input type="submit" name="Submit" value="Reserve">
<a class="button" href="logout.php">Log out</a>
</div> </center>
</form>
<?php
else {
header("location: reservation.php");
}
?>
My code is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="scripts/jquery.validate.min.js"></script>
<style type="text/css">
#addItemContainer {
background-color: rgba(204,207,232,1);
}
</style>
<script type="text/javascript">
var flag=0;
</script>
</head>
<body>
<form id="list" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id="container">
<input type="submit" class="button" name="edit" id="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="hidden" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['confirmDelete']))
{
if($_POST['action']=='confirmDelete')
{
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" id="selected" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
?>
</table>
</div>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="confirmDelete" value="Delete" />
<input type="button" id="cancelDelete" class="dialogButton cancelButton" name="cancelDelete" value="Cancel" />
</div>
</div>
</form>
<div class="dialogBG">
<div id="addItemContainer" class="dialog">
<div class="closeDialog"></div>
<h1>Edit Item</h1>
<form id="data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<?php
if(isset($_POST['action']))
{
if($_POST['action']=='edit')
{
echo '<script>flag=1;</script>';
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
break;
}
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
$shop = $inRow['shop'];
$category = $inRow['category'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
}
}
?>
<div class="leftAligned">
<div class="inp">
<label for="shop">ID : </label>
<input type="text" id="id" name="id" value="<?php echo $id; ?>" required disabled>
</div> <br>
<div class="inp">
<label for="shop">Shop : </label>
<input type="text" id="shop" name="shop" value="<?php echo $shop; ?>" required>
</div> <br>
<div class="inp">
<label for="category">Category : </label>
<input type="text" id="category" name="category" value="<?php echo $category; ?>" required>
</div> <br>
<div class="inp">
<label for="item">Item : </label>
<input type="text" id="item" name="item" value="<?php echo $item; ?>" required>
</div> <br>
<div class="inp">
<label for="qnty">Quantity : </label>
<input type="text" id="qnty" name="qnty" value="<?php echo $qnty; ?>" required>
</div> <br>
<div class="inp">
<label for="unit">Unit : </label>
<input type="text" id="unit" name="unit" value="<?php echo $unit; ?>" required>
</div> <br>
<div class="inp">
<label for="price_based_on">Price based on : </label>
<select name="price_based_on" id="price_based_on">
<option value="kilos">Kilos</option>
<option value="packet">Packet</option>
<option value="bottle">Bottle</option>
<option value="box">Box</option>
<option value="piece">Piece</option>
</select>
</div> <br>
<div class="inp">
<label for="mrp">MRP (₹) : </label>
<input type="text" id="mrp" name="mrp" value="<?php echo $mrp; ?>" required>
</div> <br>
<div class="inp">
<label for="sellers_price">Seller's Price (₹) : </label>
<input type="text" id="sellers_price" value="<?php echo $sellers_price; ?>" name="sellers_price" required>
</div> <br>
<div class="inp">
<label for="last_updated_on">Last Updated on : </label>
<input type="date" id="last_updated_on" name="last_updated_on" value="<?php echo $last_updated_on; ?>" required>
</div>
</div>
<div class="inp">
<input id="insertButton" type="submit" name="submit" value="Insert">
</div>
<div id="message">
<?php
if(isset($_POST['submit']))
{
echo "<script> alert('$id'); </script>";
$shop = $_POST['shop'];
$category = $_POST['category'];
$item = $_POST['item'];
$qnty = $_POST['qnty'];
$unit = $_POST['unit'];
$price_based_on = $_POST['price_based_on'];
$mrp = $_POST['mrp'];
$sellers_price = $_POST['sellers_price'];
$last_updated_on = $_POST['last_updated_on'];
$result=null;
$query = "UPDATE grocery SET shop='$shop', category='$category', item='$item', quantity='$qnty', unit='$unit', price_based_on='$price_based_on', mrp='$mrp', sellers_price='$sellers_price', last_updated_on='$last_updated_on' WHERE id='$id'";
if(!empty($shop)&&!empty($category)&&!empty($item)&&is_numeric($qnty)&&!empty($unit)&&is_numeric($mrp)&&is_numeric($sellers_price)&&!empty($last_updated_on))
{
$result = mysqli_query($dbc, $query)
or die(mysqli_error($dbc));
}
if($result)
{
echo '<span class="success">Item Edited Successfully!</span>';
}
else
{
echo '<span class="failure">Failed to insert Item.</span>';
}
//header("Refresh:2");
}
?>
<script>
$(document).ready(function(){
$( "#data" ).validate({
rules: {
qnty: {
number: true
},
mrp: {
number: true
},
sellers_price: {
number: true
}
},
messages: {
qnty : {
number: '<br> <span class="failure err">Enter a valid quantity</span>'
},
mrp : {
number: '<br> <span class="failure err">Enter a valid MRP</span>'
},
sellers_price : {
number: '<br> <span class="failure err">Enter a valid Price</span>'
},
}
});
});
</script>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(event){
if($(this).val()=="Delete")
{
$("#deleteConfirmDialog").show(200).parent(".dialogBG").fadeIn(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
event.preventDefault();
$("#action").val('edit');
$("#list").submit();
}
});
if(flag===1)
{
console.log("This shouldn't be there if the page reloads!");
$("#addItemContainer").show(200).parent(".dialogBG").fadeIn(200);
}
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
$("input:checkbox[name='selected[]']").prop('checked', false);
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
});
</script>
<?php
mysqli_close($dbc);
?>
</body>
</html>
Notice that I obtain the id of the first selected element by using the lines:
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
break;
}
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
Now, I use the id(which is exactly the same as edit_id) thus obtained to access the record in the DB, and show it in the popup.
<div class="leftAligned">
<div class="inp">
<label for="shop">ID : </label>
<input type="text" id="id" name="id" value="<?php echo $id; ?>" required disabled>
</div> <br>
<div class="inp">
<label for="shop">Shop : </label>
<input type="text" id="shop" name="shop" value="<?php echo $shop; ?>" required>
</div> <br>
<div class="inp">
<label for="category">Category : </label>
<input type="text" id="category" name="category" value="<?php echo $category; ?>" required>
</div> <br>
<div class="inp">
<label for="item">Item : </label>
<input type="text" id="item" name="item" value="<?php echo $item; ?>" required>
</div> <br>
<div class="inp">
<label for="qnty">Quantity : </label>
<input type="text" id="qnty" name="qnty" value="<?php echo $qnty; ?>" required>
</div> <br>
<div class="inp">
<label for="unit">Unit : </label>
<input type="text" id="unit" name="unit" value="<?php echo $unit; ?>" required>
</div> <br>
<div class="inp">
<label for="price_based_on">Price based on : </label>
<select name="price_based_on" id="price_based_on">
<option value="kilos">Kilos</option>
<option value="packet">Packet</option>
<option value="bottle">Bottle</option>
<option value="box">Box</option>
<option value="piece">Piece</option>
</select>
</div> <br>
<div class="inp">
<label for="mrp">MRP (₹) : </label>
<input type="text" id="mrp" name="mrp" value="<?php echo $mrp; ?>" required>
</div> <br>
<div class="inp">
<label for="sellers_price">Seller's Price (₹) : </label>
<input type="text" id="sellers_price" value="<?php echo $sellers_price; ?>" name="sellers_price" required>
</div> <br>
<div class="inp">
<label for="last_updated_on">Last Updated on : </label>
<input type="date" id="last_updated_on" name="last_updated_on" value="<?php echo $last_updated_on; ?>" required>
</div>
</div>
The ID and all the relevant details thus far are exactly as they should be.
However, further down, when I try to use the ID to update the record, using the statement
UPDATE grocery SET shop='$shop', category='$category', item='$item',
quantity='$qnty', unit='$unit', price_based_on='$price_based_on',
mrp='$mrp', sellers_price='$sellers_price',
last_updated_on='$last_updated_on'
WHERE id='$id'
somehow the id has changed to the last value of id in the table. So, instead of updating the table's correct record with the updated values, since the id "magically" changes at this point (after the sumbit button has been pressed), the last value of the id appears. I want the id to stay the same as the original id.
Why is this happening and how can I solve this?
How to Insert and update using one form in php. Insert and Update not working
what to do. I have file productinsert.php and one file for display data displayProduct.php when i am inserting data are not inserted and it redirect on same page it not displaying data on addProduct.php also not updating plz help
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<?php
include('header1.php');
?>
</head>
<body>
<?php
include('sidenav.php');
?>
<div id="page-wrapper" >
<div id="page-inner">
<div class="row">
<div class="col-md-12">
<h2>Add Product</h2>
</div>
</div>
<!-- /. ROW -->
<hr />
<div class="row">
<?php
include('config.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(isset($_POST['submit']))
{
$fileName=$_FILES["filepdf"]["name"];
$fileSize=$_FILES["filepdf"]["size"]/2024;
$fileType=$_FILES["filepdf"]["type"];
$fileTmpName=$_FILES["filepdf"]["tmp_name"];
if($fileType=="application/pdf"){
if($fileSize<=200){
//New file name
$random=rand(1111,9999);
$newFileName=$random.$fileName;
//File upload path
$uploadPath="testUpload/".$newFileName;
//function for upload file
if(move_uploaded_file($fileTmpName,$uploadPath))
{
echo "Successful<BR>";
echo "File Name :".$newFileName."<BR>";
echo "File Size :".$fileSize." kb"."<BR>";
echo "File Type :".$fileType."<BR>";
}
else
{
echo "Maximum upload file size limit is 200 kb";
}
}
else
{
return false;
echo "You can only upload a pdf doc file.";
}
echo "here downld";
$updates = isset($_POST['updates']) ? 'Yes' : 'No';
$catnm=$_POST['catnm'];
$prodnm=$_POST['prodnm'];
$prod_dtl=$_POST['prod_dtl'];
//$updates=$_POST['downld'];
$date=$_POST['date'];
$query=("insert into addproduct(catnm,prodnm,prod_dtl,pdf,downld,date)
values('$catnm','$prodnm','$prod_dtl','$uploadPath','$updates','$date')");
$result = mysql_query($query,$conn);
echo"record inserted";
if($result)
{
header("location:addProduct.php");
}
}
}
}
else if($_SERVER['REQUEST_METHOD']=='GET')
{
if(isset($_GET['id']))
{
$id = $_GET['id'];
if(isset($_POST['submit']))
{
$updates['downld'] = isset($_POST['downld']) ? 'Yes' : 'No';
$cat['catnm']=$_POST['catnm'];
$prodnm['prodnm']=$_POST['prodnm'];
$prod_dtl['prod_dtl']=$_GET['prod_dtl'];
$pdf['pdf']=$_GET['pdf'];
$downld['downld']=$_GET['downld'];
$date['date']=$_GET['date'];
$query3=mysql_query("update addproduct set catnm='$cat',
prodnm='$prodnm',prod_dtl='$prod_dtl'
,pdf='$pdf',downld='$updates',date='$date' where id='$id'");
if($query3)
{
header('location:addProduct.php');
}
}
$query1=mysql_query("select * from addproduct where id='$id'");
$query4=mysql_fetch_array($query1);
//echo "<pre>";
//print_r($query4);
}
}
?>
<div class="col-md-6 col-sm-12 col-xs-12">
<div class="panel-body">
<form role="form" method="get" enctype="multipart/form-data"
name="myform" action= "<?php echo $_SERVER['PHP_SELF'];?>">
<br/>
<label>Select Category:</label>
<div class="form-group">
<?php
include('config.php');
$query1=mysql_query("select catnm from addcategory");
?>
<select class=form-control m-b-10 name=catnm id=catnm >
<?php
echo"<option>---Select---</option required>";
while($query=mysql_fetch_array($query1))
{
$selectedCat = '';
if($query[catnm] == $query4['catnm'])
{
$selectedCat = "selected";
}
echo "<option value='$query[catnm]' $selectedCat >$query[catnm]</option>";
}
?>
</select>
<br/>
<div class="form-group">
<input type="text" class="form-control" id="prodnm"
placeholder="Product Name" name="prodnm" required
value= "<?php $query4['prodnm']; ?>"/>
</div>
<div class="form-group">
<textarea class="form-control" id="catdtl" name="catdtl"
placeholder="Product Detail" "rows="10" cols="62" required>
<?php echo $query4['prod_dtl']; ?>
</textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">PDF File</label>
<input type="file"
id="exampleInputFile" accept="application/pdf" name="filepdf" required >
file : <?php echo $query4['pdf']; ?>
</div>
<div class="checkbox">
<label>
<input id="checkbox" type="checkbox" name="updates" required
/> Is Downloadable <br />
</label>
</div>
<input type="text"
placeholder="Date of Upload" id="" name="date" required />
<div style="padding-top:20px;padding-bottom:40px;width:650px;">
<input type="submit" name="submit" id="button" tabindex="2"/>
<hr/>
</form>
<?php
if(isset($_GET['id']))
{
$id=$_GET['id'];
if(isset($_POST['submit']))
{
$updates['downld'] = isset($_POST['downld']) ? 'Yes' : 'No';
$cat['catnm']=$_POST['catnm'];
$prodnm['prodnm']=$_POST['prodnm'];
$prod_dtl['prod_dtl']=$_GET['prod_dtl'];
$pdf['pdf']=$_GET['pdf'];
$downld['downld']=$_GET['downld'];
$date['date']=$_GET['date'];
$query3=mysql_query("update addproduct set catnm='$cat',
prodnm='$prodnm',prod_dtl='$prod_dtl'
,pdf='$pdf',downld='$updates',date='$date' where id='$id'");
if($query3)
{
header('location:addProduct.php');
}
}
}
?>
</div>
<!-- /. ROW -->
</div>
<!-- /. PAGE INNER -->
</div>
<!-- /. PAGE WRAPPER -->
</div>
</body>
</html>
When is need to update add to form a hidden filed with id equal to row to update and name id. If need to insert don't use id row.
<form>
if(isset($_GET['update'])) echo '<input type="hidden" name="id" value="'.$_GET['id'].'">';
</form>
if(isset($_POST['id'])) { do sql to update where id=$_POST['id']; } else {do sql to insert}
Also to update you need to fill inputs with existing data from DB like this
<input value="<? if(isset($_GET['update'])) echo $value; ?>">
<select> <option value="1" if(isset($_GET['update']) && select1==1) echo 'selected'; >1</options>
<option value="2" if(isset($_GET['update']) && select1==2) echo 'selected'; >2</options>
this is my html form
<?php
session_start ();
if (! isset ( $_SESSION ['is_logged_in'] )) {
header ( "Location: login.php" );
};
?>
<?php
include '../functions/process-database.php';
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Cp1252">
<title>VSN Treks Nepal :: Your Trusted Trekking Partner in Nepal</title>
<link rel="stylesheet" href="css/style.css">
<script src="../scripts/jquery-2.1.1.js"></script>
<script src="../scripts/jquery-1.11.2.js"></script>
<script src="../scripts/jquery-1.3.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(document).ready(
/* This is the function that will get executed after the DOM is fully loaded */
function () {
$( "#datepicker" ).datepicker({
changeMonth: true,//this option for allowing user to select month
changeYear: true //this option for allowing user to select from year range
});
}
);
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
<?php include 'includes/admin-header.php';?>
</div>
<!-- header ends -->
<div class="nav-bar">
<div class="main-menu">
<?php include 'includes/admin-nav-bar.php';?>
</div>
</div>
<!-- nab-bar end -->
<div class="add-activitie-content">
<h1>Add Activitie</h1>
<form action="execute/process-add-activitie.php" method="POST" enctype="multipart/form-data">
<p>
<label>Title :</label><input type="text" name="title" class="input" required>
</p>
<p>
<label>Description :</label>
<textarea name="description" class="add" required></textarea>
</p>
<p>
<label>Date :</label><input type="date" name="date" class="input" id="datepicker" required>
</p>
<p>
<label>Image :</label><input type="file" name="img" class="image" required>
</p>
<p>
<label>Category :</label> <select name="category_id" class="select" required>
<?php
$query = "SELECT * FROM category";
$result = mysqli_query ( $conn, $query );
while ( $row = mysqli_fetch_assoc ( $result ) ) {
?>
<?php echo "<option value='". $row['id'] ."'>". $row['title'] ."</option>" ?>
<?php } // endwhile; ?>
</select>
</p>
<p>
<label>Status :</label> <select name="status" class="status" required>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</p>
<p>
<input type="submit" name="submit" value="Add Activitie" class="submit">
</p>
</form>
</div>
<!-- add-activitie-content end -->
<div class="footer">
<div class="main-footer">
<?php include 'includes/admin-footer.php';?>
</div>
</div>
<!-- footer end -->
</div>
<!-- wrapper end -->
</body>
</html>
This is my php processing page
<?php
include '../../functions/process-database.php';
print_r($_POST);
if (isset($_POST['submit']) && $_POST['submit'] == "Add Activitie") {
echo "works";
$title = $_POST['title'];
$description = $_POST['description'];
$date = $_POST['date'];
$category_id = $_POST['category_id'];
$status = $_POST['status'];
if (! empty ( $_FILES )) {
$image = time () . "-" . basename ( $_FILES ['img'] ['name'] );
move_uploaded_file ( $_FILES ['img'] ['tmp_name'], "../../images/activities/$image" );
} else {
echo "Error: No Image Selected"; exit ();
}
$query = "INSERT INTO `activitie`(`title`, `description`, `date`, `image`, `category_id`, `status`) VALUES ('$title','$description','$date','$image','$category_id','$status')";
$result = mysqli_query ( $conn, $query );
print_r($_POST);exit;
if ($result) {
header('Location: ../display-activitie.php');
} else {
die ( mysqli_error () );
}
}
Change that:
<input type="submit" name="submit" value="Add Activitie" class="submit">
to
<input type = "hidden" name = "submit" value = "Add Activitie"/>
<input type = "submit" value = "Add Activitie" class = "submit">