keeping history of form data using session - php

I have a form that users can utilize to introduce some data to create a badge. I'm using session so that i can keep like a little history list for the users, and also if they click on one element from that list the data will be sent to the form automatically. My problem is that when i click on one element from the list a new row is inserted containing the same data, and also if i complete the form with identical data that i already have in my list again it creates another line containing the same data that i already have once. Can i do something so that my history list to contain only unique values, basically to not have the same line multiple times.
This is my code for the form:
<form method="get" autocomplete="off">
<h3>Creaza ecuson</h3>
<label>
Nume:<br><input type="text" name="nume" id="nume" required value="<?php echo $search->nume ?>"><br>
Prenume:<br><input type="text" name="prenume" id="prenume" required value="<?php echo $search->prenume ?>"><br>
Sex:<br><div class="autocomplete" style="width:300px;">
<input id="sex" type="text" name="sex" required value="<?php echo $search->sex ?>">
</div><br><br>
Rol:<br><div class="autocomplete" style="width:300px;">
<input id="rol" type="text" name="rol" required value="<?php echo $search->rol ?>">
</div><br><br>
Culoare text:<br><input type="color" name="cul" id="cul" value="<?php echo $search->cul ?>"><br><br>
Font ecuson:<br><div class="autocomplete" style="width:300px;">
<input id="font" type="text" name="font" required value="<?php echo $search->font ?>">
</div><br><br>
Format ecuson (portrait or landscape):<br><div class="autocomplete" style="width:300px;">
<input id="format" type="text" name="format" required value="<?php echo $search->format ?>">
</div><br><br>
</label>
<input type="submit" name="history" value="History" />
<button type="button" onclick="create()">Creaza</button><br><br>
</form>
My session code:
<?php
session_start();
$search = parseRequest();
storeSearch($search);
include "form.php";
$searches = $_SESSION['searches'];
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty()) {
$_SESSION['searches'][] = $search;
}
}
function parseRequest() {
$search = new SearchRequest;
$search->nume = !empty($_GET['nume']) ? $_GET['nume'] : "";
$search->prenume = !empty($_GET['prenume']) ? $_GET['prenume'] : "";
$search->sex = !empty($_GET['sex']) ? $_GET['sex'] : "";
$search->rol = !empty($_GET['rol']) ? $_GET['rol'] : "";
$search->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$search->font = !empty($_GET['font']) ? $_GET['font'] : "";
$search->format = !empty($_GET['format']) ? $_GET['format'] : "";
return $search;
}
/**
* search request
*/
class SearchRequest
{
public $nume = "";
public $prenume = "";
public $sex = "";
public $rol = "";
public $cul = "";
public $font = "";
public $format = "";
function toQueryString() {
$params = [
'nume' => $this->nume,
'prenume' => $this->prenume,
'sex' => $this->sex,
'rol'=> $this->rol,
'cul'=> $this->cul,
'font'=> $this->font,
'format'=> $this->format
];
return http_build_query($params);
}
function isEmpty() {
return !$this->nume || !$this->prenume || !$this->sex || !$this->rol || !$this->cul || !$this->font || !$this->format;
}
}
?>
And the so called history code:
<?php
foreach ($searches as $s) {
?>
<li><a href="creare.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->nume?> - <?php echo $s->prenume?> - <?php echo $s->sex?> - <?php echo $s->rol?> - <?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?>
</a></li>
<?php
}
?>
I don't think the script with the autocomplete function needs to be posted here for the question that i asked. If needed i will provide.

perhaps something as simple as
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty() && !in_array($search,$_SESSION['searches') {
$_SESSION['searches'][] = $search;
}
}

Building on CFP Support's answer, here's a slightly different approach to how I would create the form and handler. It's very similar to yours but I structured the logic a bit differently. I only added 3 fields from your form but you can easily add the remaining fields.
Fiddle - http://phpfiddle.org/lite/code/354t-6sgn
<?php
session_start();
// Initialize the cart if it needs it.
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Should we show cart?
$showCart = isset($_GET['cart']) && $_GET['cart'] === 'true';
// Should we clear the cart?
if (isset($_GET['clear']) && $_GET['clear'] === 'true') {
$_SESSION['cart'] = [];
}
// Grab the current cart.
$cart = $_SESSION['cart'];
// The form was submitted
if (isset($_POST['submit'])) {
// Copy the POST data into a variable so we can modify it without side effects.
$formData = $_POST;
// Remove the submit button from the form data
unset($formData['submit']);
// Check if it is in the cart already.
if (!in_array($formData, $cart)) {
// If not, then add it.
$cart[] = $formData;
}
// Store the cart in the session.
$_SESSION['cart'] = $cart;
}
?>
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<form method="post" autocomplete="off">
<h3>Creaza ecuson</h3>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="nume">Nume:
<input type="text" name="nume" id="nume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="prenume">Prenume:
<input type="text" name="prenume" id="prenume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="sex">Sex:
<input type="text" name="sex" id="sex" class="form-control" required>
</label>
</div>
</div>
<button class="btn btn-primary" name="submit" type="submit">Create</button>
<?php
// Toggle show/hide history
if ($showCart) { ?>
<a class="btn btn-primary" href="?" role="button">Hide Cart</a>
<?php } else { ?>
<a class="btn btn-primary" href="?cart=true" role="button">Show Cart</a>
<?php }
// If the cart is not empty, allow user to clear it.
if (!empty($cart)) { ?>
<a class="btn btn-primary" href="?clear=true" role="button">Clear Cart</a>
<?php }
?>
</form>
<?php
// Show the cart.
if ($showCart) {
echo '<pre>';
var_dump($cart);
echo '</pre>';
}
?>
</div>
</body>
</html>

Here's a way and little pseudo-code, you could implement something similar with your codebase.
The idea is, since from one computer only one person can sign up, store a unique ID for that person in session. Then when entering the data into session, check if that ID is present or not.
If it's present, do not add, if it's not, add.
Pseudo-code
$uniqueID = hash("sha256", $_SERVER['REMOTE_ADDR']); //generate a unique ID depending on IP since that would be unique for each computer
//insert into your session
if(!in($sessionHandler, $uniqueid)
{
//insert now
}

Related

I don't know what i did wrong on my code, the error message for php form validation stopped working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what I did wrong on my code, the error message for php form validation stopped working.
It was working perfectly until i added value attribute to the input so that the user input will persist even if the page refresh and didn't deliver due to typeError.
The form does'nt show any error again but my reason for adding the value attribute is working.
I'm learning php, please help me to understand why i'm having the issue.
I don't understand because i'm not getting any error from php.
This is my code
<?php
// empting the value variables when user have'nt typed anything to prevent error. This is the shorthand of typing samething that's going to have the same value
$email = $title = $ingredients = '';
// put out the error on the html instead of echoing it
// so i used array so that i can neatly put out all the errors instead of using different variables for all
$error = array('email' => '', 'title' => '', 'ingredients' => '');
// check if the form was clicked and retrive the values sent
// i will achieve this by using a default method called isset() and i will check if value is contained in the form using the submit btn, this is because when a user clicks on the form submit, the user have entered a value
if(isset($_POST['submit'])){
// check if the field submited is empty
// we achieve this using a default method called empty()
// we check them one field at a time
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value=" <?php echo $email ?> ">
<div class="error_msg"><?php echo $error['email']; ?></div>
</div>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value=" <?php echo $title ?> " >
<div class="error_msg"><?php echo $error['title']; ?></div>
</div>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value=" <?php echo $ingredients ?> ">
<div class="error_msg"><?php echo $error['ingredients']; ?></div>
</div>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Other then the issues with whitespace in your inputs you should also be aware of XSS when inserting the values back into the form (like using " would break the form) and also don't populate the errors till needed, this will allow you to easily continue and do the success step without needing to loop over the $errors array and it also allows you to hide the <div class="error_msg"></div> element and only show when there is an error.
Also your missing <head> and <body>, presuming they are in the includes, but doing it that way would make it rather difficult to add additional elements or scripts.
<?php
$email = $title = $ingredients = '';
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check for email
if (empty($_POST['email'])) {
$error['email'] = 'Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if (empty($_POST['title'])) {
$error['title'] = 'Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if (empty($_POST['ingredients'])) {
$error['ingredients'] = 'Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
if (empty($error)) {
// do some thing with $email, $title, $ingredients
die(header('Location: ./thank-you.php'));
}
}
function xss_safe($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?><!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php' ?>
<form action="form.php" method="POST">
<div class="input_div">
<label>Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>"/>
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>"/>
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>"/>
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
</div>
<div class="input_div">
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Seeing as your error checking is merely for empty/missed input fields it's easier to just make the inputs required as per HTML5. Here's a simplified version using placeholders for information after the form has been submitted.
Warning: If you are going to be inserting this data into a MySQL table, you need to sanitize the inputs first!
<?php
$email = $title = $ingredients = "";
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$title = $_POST["title"];
$ingredients = $_POST["ingredients"];
}
echo "
<form method='POST'>
<label>Email:</label>
<input type='email' name='email' placeholder='$email' required>
<label>Pizza Title:</label>
<input type='text' name='title' placeholder='$title' required>
<label>Ingredients (comma seperated):</label>
<input type='text' name='ingredients' placeholder='$ingredients' required>
<input type='submit' name='submit' value='Submit'>
</form>
";
?>

PHP - Validate if textbox has a value or not?

I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>

Unable to connect the Database and Handle the POST request

Hello I am working with a predefined template and I am trying to fetch some data from the input space in form of POST/GET request using php. But I am unable to do so, How can I integrate the database and handle the php parameters?
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
?>
}
Hello change your code to this
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</div>
For the database connection it depends on which database you are working with but you can start here. A simple Google query with provide you what you are looking for
I put together an example for you that may come in handy. This shows how you can use PHP to submit a form print some values that the user enters on the page. I also included some commented out code that you can copy and move to a seperate script and call by changing the action value to the file path.
The PHP script:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
$data = [
"BOB" => "AWESOME",
"JOE" => "AVERAGE",
"TOM" => "COOL"
];
}
?>
Next, we have the form. I added this form because you need it to submit to the page. (Well you don't "need" it but it makes life easy.)
<div class="container">
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Adhaar"
name="adhaar"
required
value="<?= isset($_POST['adhaar']) ? $_POST['adhaar'] : '' ?>">
</div>
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Town/City"
name="city"
required
value="<?= isset($_POST['city']) ? $_POST['city'] : '' ?>">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">CLICK ME!</button>
</div>
</form>
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
</div>
Last piece of the file simply outputs information onto the page if it finds it in the $_POST global array.
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
This commented out part here you can use to pull data from the database and pass it back to your page. If you are just starting it's cool to tinker but ideally you DO NOT want to make calls to the db on the same page as your view. It should live in it's own file.
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
You should Try This Code ..This is working i Simply add a submit button to it
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<form method="GET" action="xxx.php">
<input type="text" placeholder="Adhaar" name="Adhaar" required="" />
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="" />
<input type="submit" name="submit" value="show">
<?php
if(isset($_GET['submit']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</form>
</div>

My GET statements work correctly but my POST statements don't

I've been fiddling with this for hours and cant figure out why the $_GET statements perform correctly, but the $_POST statements don't.
IF $stock is in dB, show values in the form, and if the form is submitted submit UPDATE those values, IF $stock is NOT in dB and the form is submitted INSERT into table. Neither $_POST statement seems to work, yet are not throwing any errors, just redirecting back to the same page when you hit the submit button.
include_once ('../helper_content/sql_Connect.php');
$error = array();
$KBB_Low = "";
$KBB_High = "";
$KBB_Fair = "";
$KBB_Retail = "";
$KBB_URL = "";
$TrueCar_Great = "";
$TrueCar_Average = "";
$TrueCar_Above = "";
$TrueCar_URL = "";
$NADA_Trade = "";
$NADA_Loan = "";
$NADA_Retail = "";
# Was the form submitted via POST?
if(isset($_POST['Submit'])) {
# Yes
# Is this a new stock item?
if(empty($_POST['stock'])) {
# Yes - insert
$kbb_low = filter_var($_POST['kbb_low'], FILTER_SANITIZE_STRING);
$kbb_high = filter_var($_POST['kbb_high'], FILTER_SANITIZE_STRING);
$kbb_fair = filter_var($_POST['kbb_fair'], FILTER_SANITIZE_STRING);
$kbb_retail = filter_var($_POST['kbb_retail'], FILTER_SANITIZE_STRING);
$kbb_url = filter_var($_POST['kbb_url'], FILTER_SANITIZE_STRING);
$truecar_great = filter_var($_POST['truecar_great'], FILTER_SANITIZE_STRING);
$truecar_average = filter_var($_POST['truecar_average'], FILTER_SANITIZE_STRING);
$truecar_above = filter_var($_POST['truecar_above'], FILTER_SANITIZE_STRING);
$truecar_url = filter_var($_POST['truecar_url'], FILTER_SANITIZE_STRING);
$nada_trade = filter_var($_POST['nada_trade'], FILTER_SANITIZE_STRING);
$nada_loan = filter_var($_POST['nada_loan'], FILTER_SANITIZE_STRING);
$nada_retail = filter_var($_POST['nada_retail'], FILTER_SANITIZE_STRING);
if ($stmt = $conn->prepare("INSERT INTO `Inventory_Valuations` (`stock`,
`kbb_low`, `kbb_high`, `kbb_fair`, `kbb_retail`, `kbb_url`,
`truecar_great`, `truecar_average`, `truecar_above`, `truecar_url`,
`nada_trade`, `nada_loan`, `nada_retail`
) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param('iiiisiiisiii', $stock,
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail
);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?inserted=true');
exit();
} else {
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
} else {
# No - update
$stock = $_POST['stock'];
$kbb_low = $_POST['kbb_low'];
$kbb_high = $_POST['kbb_high'];
$kbb_fair = $_POST['kbb_fair'];
$kbb_retail = $_POST['kbb_retail'];
$kbb_url = $_POST['kbb_url'];
$truecar_great = $_POST['truecar_great'];
$truecar_average = $_POST['truecar_average'];
$truecar_above = $_POST['truecar_above'];
$truecar_url = $_POST['truecar_url'];
$nada_trade = $_POST['nada_trade'];
$nada_loan = $_POST['nada_loan'];
$nada_retail = $_POST['nada_retail'];
/*... get variables from the $_POST array */
if ($stmt = $conn->prepare("UPDATE `Inventory_Valuations` SET
kbb_low=?, kbb_high=?, kbb_fair=?, kbb_retail=?, kbb_url=?,
truecar_great=?, truecar_average=?, truecar_above=?, truecar_url=?,
nada_trade=?, nada_loan=?, nada_retail=?
WHERE stock=?")) {
$stmt->bind_param('iiiisiiisiii',
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail,
$stock);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else {
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated'])) {
$message = "Record updated";
}
else if(isset($_GET['inserted'])) {
$message = "Record added into database";
}
if($stock != "") {
# Load the item?
$query = "SELECT * FROM `Inventory_Valuations` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $stock);
if($stmt->execute()) {
$result = $stmt->get_result();
if($result) {
$row = $result->fetch_assoc();
$KBB_Low = $row['kbb_low'];
$KBB_High = $row['kbb_high'];
$KBB_Fair = $row['kbb_fair'];
$KBB_Retail = $row['kbb_retail'];
$KBB_URL = $row['kbb_url'];
$TrueCar_Great = $row['truecar_great'];
$TrueCar_Average = $row['truecar_average'];
$TrueCar_Above = $row['truecar_above'];
$TrueCar_URL = $row['truecar_url'];
$NADA_Trade = $row['nada_trade'];
$NADA_Loan = $row['nada_loan'];
$NADA_Retail = $row['nada_retail'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>?cat=Sales&stock=<?= $stock; ?>">
<section class="valuations">
<h3>Valuations</h3>
<input type="hidden" name="stock" value="<?= $stock; ?>">
<div>
<a target="_blank" href="<?=$KBB_Link; ?>"><img src="images/logos/KBB.png"></a>
<p>
<label for="kbb_low">Fair Market Range</label>
<input type="number" class="dollars" id="kbb_low" name="kbb_low" placeholder="Low" value="<?= $KBB_Low; ?>"> -
<input type="number" class="dollars" id="kbb_high" name="kbb_high" placeholder="High" value="<?= $KBB_High; ?>">
</p>
<p>
<label for="kbb_fair">Fair Price</label>
<input type="number" class="dollars" id="kbb_fair" name="kbb_fair" placeholder="Fair" value="<?= $KBB_Fair; ?>">
</p>
<p>
<label for="kbb_retail">Sug. Retail</label>
<input type="number" class="dollars" id="kbb_retail" name="kbb_retail" placeholder="Retail" value="<?= $KBB_Retail; ?>">
</p>
<p class="clear">
<label for="kbb_url">Report URL</label>
<input type="url" id="kbb_url" name="kbb_url" size="20" spellcheck="false" placeholder="www.kbb.com/" value="<?= $KBB_URL; ?>">
<i title="Copy KBB URL" data-clipboard-target="#kbb_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<img src="images/logos/TrueCar.png">
<p><label for="truecar_great">Great Price</label> <input type="number" class="dollars" id="truecar_great" name="truecar_great" placeholder="Great" value="<?= $TrueCar_Great; ?>"></p>
<p><label for="truecar_average">Average Price</label> <input type="number" class="dollars" id="truecar_average" name="truecar_average" placeholder="Average" value="<?= $TrueCar_Average; ?>"></p>
<p><label for="truecar_above">High Price</label> <input type="number" class="dollars" id="truecar_above" name="truecar_above" placeholder="Above" value="<?= $TrueCar_Above; ?>"></p>
<p class="clear">
<label for="truecar_url">Report URL</label> <input type="url" id="truecar_url" name="truecar_url" size="20" spellcheck="false" placeholder="www.truecar.com/" value="<?= $TrueCar_URL; ?>">
<i title="Copy TrueCar URL" data-clipboard-target="#truecar_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<a target="_blank" href="http://www.nadaguides.com/Cars/<?= $year; ?>/<?= $make; ?>/<?= $model; ?>"><img src="images/logos/NADA.png"></a>
<p><label for="nada_trade">Trade</label> <input type="number" class="dollars" id="nada_trade" name="nada_trade" placeholder="Trade" value="<?= $NADA_Trade; ?>"></p>
<p><label for="nada_loan">Loan</label> <input type="number" class="dollars" id="nada_loan" name="nada_loan" placeholder="Loan" value="<?= $NADA_Loan; ?>"></p>
<p><label for="nada_retail">Retail</label> <input type="number" class="dollars" id="nada_retail" name="nada_retail" placeholder="Retail" value="<?= $NADA_Retail; ?>"></p>
</div>
<input type="submit" id="Submit" value="Submit">
</form>
<script src="include/js/clipboard.min.js"></script>
<script>
var clipboard = new Clipboard('.fa-clipboard');
clipboard.on('success', function(e) {console.log(e);});
clipboard.on('error', function(e) {console.log(e);});
</script>
Replace
if(isset($_POST['Submit']))
with
if (!empty($_POST))
this checks in general if anything has been posted (if the POST request is not empty -> do this)
Please verify your submit have this ...
<input type="submit" value="Submit" name="submit" />
and your form method is
<form method="POST" action="xyz"> ...
Your code is a bit off.
You're checking
if(isset($_POST['Submit'])) {
Which is not being posted at all. This is why, the if part never gets executed.
You can try to check if it is POST request by
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
maybe this helps.
You should use filter_input to handle POST and GET params. Using $_POST or $_GET is deprecated.

PHP MySQL not updating for CRUD app

I'm attempting to add the update function to my CRUD application. Essentially it uses the database specified, and uses the 'id' from the index.php page, which is 'productID' from the database. In another part of the application, a store management feature is included with the same skeleton Update page and works perfectly.
The database (Product) contains productID(PK), productName, productPrice, storeID(FK), productDate, productComments, productQuantity, and productPortion.
I'm certain it's within the PHP script, likely around the UPDATE command after using a few error checks but I can't seem to figure out what might be the main issue.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update an Item</h3>
</div>
<form class="form-horizontal" action="update.php" method="post">
<input type="hidden" name="productID" value="<?php echo $id ?>">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Item</label>
<div class="controls">
<input name="productName" type="text" placeholder="Product Name" value="<?php echo !empty($productName)?$productName:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="productPrice" type="number" step="any" placeholder="Price" value="<?php echo !empty($productPrice)?$productPrice:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($storeError)?'error':'';?>">
<label class="control-label">Store</label>
<div class="controls">
<select name="storeID" class="form-control">
<option value="">Select Store</option>
<?php $pdo=D atabase::connect(); $sql='SELECT * FROM Store ORDER BY storeName DESC' ; foreach ($pdo->query($sql) as $row) { $selected = $row['storeID']==$storeID?'selected':''; echo '
<option value="'. $row['storeID'] .'" '. $selected .'>'. $row['storeName'] .'</option>'; } Database::disconnect(); ?>
</select>
<?php if (!empty($storeError)): ?>
<span class="help-inline"><?php echo $storeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($dateError)?'error':'';?>">
<label class="control-label">Date</label>
<div class="controls">
<input name="productDate" type="date" step="any" placeholder="Date" value="<?php echo !empty($productDate)?$productDate:'';?>">
<?php if (!empty($dateError)): ?>
<span class="help-inline"><?php echo $dateError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($commentsError)?'error':'';?>">
<label class="control-label">Comments</label>
<div class="controls">
<input name="productComments" type="text" placeholder="Comments" value="<?php echo !empty($productComments)?$productComments:'';?>">
<?php if (!empty($commentsError)): ?>
<span class="help-inline"><?php echo $commentsError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($quantityError)?'error':'';?>">
<label class="control-label">Quantity</label>
<div class="controls">
<input name="productQuantity" type="number" placeholder="Quantity" value="<?php echo !empty($productQuantity)?$productQuantity:'';?>">
<?php if (!empty($quantityError)): ?>
<span class="help-inline"><?php echo $quantityError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($portionError)?'error':'';?>">
<label class="control-label">Portion</label>
<div class="controls">
<input name="productPortion" type="number" placeholder="Portion" value="<?php echo !empty($productPortion)?$productPortion:'';?>">
<?php if (!empty($portionError)): ?>
<span class="help-inline"><?php echo $portionError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
<!-- /container -->
</body>
</html>
PHP
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$priceError = null;
$storeError = null;
$dateError = null;
$quantityError = null;
$portionError = null;
// keep track post values
$id = $_POST['id'];
$storeID= $_POST['storeID'];
$productName = $_POST['productName'];
$productPrice = $_POST['productPrice'];
$productQuantity = $_POST['productQuantity'];
$productPortion = $_POST['productPortion'];
$productComments = $_POST['productComments'];
$productDate = $_POST['productDate'];
//error displayed for creation errors
$valid = true;
if (empty($productName)) {
$nameError = 'Please enter the name of the product';
$valid = false;
}
if (empty($productPrice)) {
$priceError = 'Please enter a price';
$valid = false;
}
if (empty($storeID)) {
$storeError = 'Please enter a store';
$valid = false;
}
if (empty($productDate)) {
$dateError = 'Please enter the purchase date';
$valid = false;
}
if (empty($productComments)) {
$commentsError = 'Please enter any comments';
$valid = false;
}
if (empty($productQuantity)) {
$quantityError = 'Please select the quantity';
$valid = false;
}
if (empty($productPortion)) {
$portionError = 'Please enter the portion';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Product SET productName=?, productPrice=?, storeID=?, productDate=?,
productComments=?, productQuantity=?, productPortion=? WHERE productID=?";
$q = $pdo->prepare($sql);
$q->execute(array($productName,$productPrice,$storeID,$productDate,
$productComments,$productQuantity,$productPortion,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Product WHERE productID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$productName = $data['productName'];
$productPrice = $data['productPrice'];
$storeID = $data['storeID'];
$productQuantity = $data['productQuantity'];
$productPortion = $data['productPortion'];
$productComments = $data['productComments'];
$productDate = $data['productDate'];
Database::disconnect();
}
?>
Having a quick look at your code you are sending the form data via $_POST and on the php script checking $_GET then grabbing the id from $_REQUEST. Try changing
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
to
if ( !empty($_POST['id'])) {
$id = $_POST['id'];
}
Hope that helps!
Thanks Donniep!
I found that the answer was actually related to the POST values after being submitted. My impression was that I could still use the value from the GET call of 'id', but I instead needed to use the actual ID value from the product DB instead. The solution turned out to be:
// keep track post values
$id = $_POST['id'];
Needed to be changed to:
// keep track post values
$id = $_POST['productID'];

Categories