简体   繁体   中英

PHP: Validate data in Update form before submitting to database

I'm still very new to php and form validation. I am currently trying to create an update form that validates before submitting the data to the database. So far I have successfully managed to update the data in the database when submitting the form.

But now I am trying to validate the data and make sure that the 4 fields are filled in and not left blank, if some of the form fields are left blank then I need the form to reload with what was already filled in on the form previously.

I have started adding in form validation into the script below but this is script I have successfully used for adding new data to a database. I'm having trouble trying to wrap my head around what I need to change to make it work for an UPDATE query. Thanks in advance

The only fields i need to update in the form is the description, img_path, location and payment.

<?php

    $mysqli = new mysqli("localhost", "root", "", "etrading");

    session_start(); //start session

    //Check that a product ID is specified for the page
     if (isset($_GET['ItemID'])) {
       $productID = $_GET['ItemID'];

    }else{
    header("Location: index.php");
    }

 if (isset($_POST['Name'])) {
    $Name = $_POST['Name'];
    $Description = $_POST['Description'];
    $img_path = $_POST['img_path'];
    $Quantity = $_POST['Quantity'];
    $Category = $_POST['Category'];
    $Location = $_POST['Location'];
    $Saletype = $_POST['Saletype'];
    $Price = $_POST['Price'];
    $Duration = $_POST['Duration'];
    $Payment = $_POST['Payment'];


$updateQuery = "UPDATE item SET Description = '$Description', img_path = '$img_path', Location = '$Location', Payment = '$Payment' WHERE ItemID= $productID";

   $mysqli->query($updateQuery);
   echo ("Product successfully updated");   
  }


 $query = "SELECT * FROM item WHERE ItemID = $productID";
    $result = $mysqli->query($query);

if($result->num_rows > 0) {
   $data = $result->fetch_array(MYSQLI_BOTH);


//prepare input data in an array
$updatedata = array($Description, $img_path, $Location, $Payment);

//prepare error list
$errors = array ();

//Validation tests and store list
  if ($Description == "" || $img_path == "" || $Location == "" || $Payment == "" ) {
   array_push($errors, "All form fields must be filled out before submitting.");
   }
  //if errors redirect back to form page and save attempted data.
    if (count($errors) > 0) {
      $_SESSION['updatedata'] = $updatedata;
      $_SESSION['errors'] = $errors;

    header("Location: ../edit.php");
      }else{
      unset($_SESSION['updatedata']);
      unset($_SESSION['errors']);
    }

   if(isset($_SESSION['errors'])) {
    $errors = $_SESSION['errors'];

     for ($errorCount = 0; $errorCount < count($errors); $errorCount++) {
     echo ("<p class='error'>Error: " . $errors[$errorCount] . "</p>");
     }
  }

 ?>


  <div id="form">
  <h2> Edit Product </h2>
  <form action="edit.php?ItemID=<?php echo $productID; ?>" method="POST" >
        <fieldset>
            <h4>Sell Your Item</h4>
            <p><label class="title" for="Name">Name:</label>
            <input type="text" placeholder="<?php echo $data['Name']; ?>" name="Name" id="Name" title="Please enter item name" 
           readonly ><br />

            <label class="title" for="Description">Description:</label>
            <textarea name="Description" rows="5" cols="33" placeholder="<?php echo $data['Description']; ?>"  id="Description" title="Please describe your item" ></textarea><br />


            <img src="../img/<?php echo $data['img_path']; ?>" />
            <br>


             Select image to upload:
             <input type="file" name="img_path" placeholder="<?php echo $data['img_path']; ?>" id="img_path" accept="image/jpg"><br>

              <label class="title" for="Quantity">Quantity:</label>
             <input type="text" placeholder="<?php echo $data['Quantity']; ?>" name="Quantity" id="Quantity" title="Number of items" readonly><br />

             <label class="title" for="Category">Category:</label>
             <input type="text" placeholder="<?php echo $data['Category']; ?>" name="Category" id="Category" Title="Category" readonly >


            <label class="title" for="Location">Location:</label>
            <input type="text" placeholder="<?php echo $data['Location']; ?>" name="Location" id="Location" title="Enter item location" ><br />

          <label class="title" for="Saletype">Sale Type:</label>
          <input type="text" placeholder="<?php echo $data['Saletype']; ?>" name="Saletype" id="Saletype" title="Sale Type" readonly >


            <label class="title" for="Price">Price: $</label>
            <input type="text" placeholder="<?php echo $data['Price']; ?>" name="Price" id="Price" title="Please enter your name" readonly><br />

            <label class="title" for="Duration">Duration:</label>
            <input type="text" placeholder="<?php echo $data['Duration']; ?>" name="Duration" id="Duration" title="End Date" readonly><br />

            <label class="title" for="Payment">Payment Type:</label>
            <input type="text" placeholder="<?php echo $data['Payment']; ?>" name="Payment" id="Payment" title="Payment" readonly > 
            <select name="Payment" id="Payment" >
                <option value="PayPal">PayPal</option>
                <option value="Bank Deposit">Bank Deposit</option>
                 <option value="Card">Credit Card</option>
            </select><br>


                <div class="submit"><input type="submit" value="submit" name="submit" /></div>
            <div class="reset"><input type="reset" /></div>

            </fieldset>


            </form>

You could use the required attribute on the HTML form. This will ensure the form can not be submitted unless there are input values.

<input type="text" required />

In your PHP file, you can use the isset() function to check all the values.

if (isset($description) && isset($img_path) && isset($description) && isset($payment))
{
     // other code
}

You should also make sure to escape the values.

if (isset($description) && isset($img_path) && isset($description) && isset($payment))
{
    $description = mysqli_real_escape_string($conn, $description);
    $img_path = mysqli_real_escape_string($conn, $img_path);
    $location = mysqli_real_escape_string($conn, $location);
    $payment = mysqli_real_escape_string($conn, $payment);

    $updateQuery = "UPDATE item SET Description = '$Description', img_path = '$img_path', Location = '$Location', Payment = '$Payment' WHERE ItemID= $productID";
    $mysqli->query($updateQuery);
}

The mysqli_real_escape_string escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

You should always do validation on both frontend and backend.

试试这个..这会工作..它对我有用..

 <input type="text" name="name" value="<?php echo $name; ?>" required="required" placeholder="Enter name">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM