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.
Try this.. this would work.. It worked for me..
<input type="text" name="name" value="<?php echo $name; ?>" required="required" placeholder="Enter name">
Related
I have a problem when uploading image into database using mysql.
When I click button for upload the image, the error comes out like this:
"Undefined index image in C:\xampp\htdocs\fyp\kemaskinipemandu.php" at line 29 and 30.
I've tried other solution from StackOverflow but it didn't work out at all. So, here is my html and my php code.
if (isset($_POST['kemaskini'])){
$email = $_SESSION['driverEmail'];
$nama = $_POST['nama'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$kp = $_POST['kp'];
$tel = $_POST['tel'];
$alamat = $_POST['alamat'];
$exdate = date('Y-m-d', strtotime($_POST['lesen']));
$class = $_POST['jenislesen'];
$image = $_FILES['image']['name'];//imageUpload
move_uploaded_file($_FILES['image']['tmp_name'], "img/".$_FILES['image']['name']);
if($password === $cpassword){
$query = "UPDATE driver SET driverName='$nama', driverPassword='$password', cpassword='$cpassword', driverICNum='$kp', contNum='$tel',
address='$alamat', licenseExDate='$exdate', class='$class', image='$image' WHERE driverID='$driverID';";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if($result)
{
?>
<script>
alert('Kemas Kini Pemandu Berjaya. ');
window.location.href="kemaskinipemandu.php";
</script>
<?php
}
}else {
?>
<script>
alert('Kata laluan tidak sama. ');
window.location.href="kemaskinipemandu.php";
</script>
<?php
}
}
and the line that have error are :
$image = $_FILES['image']['name'];//imageUpload
move_uploaded_file($_FILES['image']['tmp_name'], "img/".$_FILES['image']['name']);
Select image to upload:
<form action="kemaskinipemandu.php" method = "POST" enctype="multipart/form-data">
<center>
<?php
$email = $_SESSION['driverEmail'];
$query=" SELECT * from driver where driverID='$driverID'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$count = mysqli_num_rows($result);
if (isset($count) and ($count > 0)) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['driverName'];
$password = $row['driverPassword'];
$cpassword = $row['cpassword'];
$ic = $row['driverICNum'];
$contNum = $row['contNum'];
$address = $row['address'];
$exdate = $row['licenseExDate'];
$class = $row['class'];
$image = $row['image'];
?>
<div class="col-md-6">
<div class="form-group">
<img src="<?php echo $image ?>" height="200" width="200"/><br><br>
<div class="form-inline">
Select image to upload:
<input type="file" name="image" id="image" style="margin-left:2%"><br><br>
</div>
<label for="nama">Nama :</label>
<input type="nama" class="form-control" name="nama" value="<?php echo $name ?>" ><br>
<label for="email">Email :</label>
<input type="email" class="form-control" name="email" value="<?php echo $email ?>" ><br>
<label for="password">Kata Laluan :</label>
<input type="password" class="form-control" name="password" value="<?php echo $password ?>" ><br>
<label for="password">Pengesahan Kata Laluan :</label>
<input type="password" class="form-control" name="cpassword" value="<?php echo $cpassword ?>" ><br>
<label for="kp">No. Kad Pengenalan :</label>
<input type="kp" class="form-control" name="kp" value="<?php echo $ic ?>" ><br>
<label for="tel">No. Tel :</label>
<input type="tel" class="form-control" name="tel" value="<?php echo $contNum ?>" ><br>
<label for="alamat">Alamat :</label>
<textarea type="alamat" class="form-control" name="alamat" rows="6"><?php echo $address ?></textarea><br>
<label for="lesen">Tamat Tempoh Lesen Memandu :</label>
<input type="date" class="form-control" name="lesen" value="<?php echo $exdate ?>" ><br>
<label for="jenislesen">Lesen/Kelas:</label>
<input type="text" class="form-control" name="jenislesen" value="<?php echo $class ?>" >
</div>
</div>
<?php } }?>
<input type="submit" class="btn btn-primary" name="kemaskini" value="Kemas Kini"></br>
</center>
</form>
I hope someone can help me. Thank you.
I'm newbie in php and i make a simple CRUD app. Unfortunately, I'm stacked with this problem, I don't know what's wrong with my code in my update.php. When i click update in my index.php it Undefined variable. I think my value in form is wrong. Any help is appreciated.
update.php
<?php
include("connection.php");
if (isset($_POST['customerNumber'])) {
$customerNumber = $_POST['customerNumber'];
$q = "SELECT customerNumber, checkNumber, paymentDate, amount FROM payments WHERE customerNumber='$customerNumber'";
$rq = mysqli_query($conn, $q);
while ($row = mysqli_feth_assoc($rq)) {
$customerNumber = $row['customerNumber'];
$checkNumber = $row['checkNumber'];
$paymentDate = $row['paymentDate'];
$amount = $row['amount'];
}
}
?>
<!-- from the index.php update -->
<form action="update.php?customerNumber=$customerNumber" method="post">
<label>
<input type="text" name="customerNumber" value="<?php echo $row['customerNumber']; ?>" placeholder="Customer Number" required>
</label>
<label>
<input type="text" name="checkNumber" value="<?php echo $row['checkNumber']; ?>" placeholder="Check Number" required>
</label>
<label>
<input type="text" name="paymentDate" value="<?php echo $row['paymentDate']; ?>" placeholder="Payment Date" required>
</label>
<label>
<input type="number" name="amount" value="<?php echo $row['amount']; ?>" placeholder="Amount">
</label>
<input type="submit" name="submit" value="update">
</form>
<?php
include('connection.php');
if (isset($_POST['submit'])) {
$customerNumber = $_POST['customerNumber'];
$checkNumber = $_POST['checkNumber'];
$paymentDate = $_POST['paymentDate'];
$amount = $_POST['amount'];
$q = "UPDATE payments SET customerNumber='$customerNumber', checkNumber='$checkNumber', paymentDate='$paymentDate', amount='$amount' WHERE customerNumber='$customerNumber' ";
$rq = mysqli_query($conn, $q);
if($rq){
header('Location: index.php');
}else{
echo "Something went wrong";
}
}
?>
I am wanting to submit a form using $_SERVER["PHP_SELF"]however its not picking up the id of the item when the form is being submitted, is there a way to add an id like the following and not have to link to another file...
<form action="process.php<?php echo"?id=$productID" ?> " method="post">
Surely there is a simple way of doing this.. I have spent alot of time googling and searching forums and nothing is giving me an explanation.
Thanks in advance.
EDIT
include "../model/functions_updateproducts.php";
function select_productspreparedGETIDt(){
global $conn;
$productID = $_GET['id'];
$nameError = "";
$sql = "SELECT * FROM product WHERE productID = :productID";
$statement = $conn->prepare($sql);
$statement->bindValue(':productID', $productID);
$statement->execute();
$result = $statement->fetchAll();
$statement->closeCursor();
foreach($result as $row):
?>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<div class="form-group">
<input type="hidden" id="productID" name="productID" value="<?php echo $row['productID'] ?>" />
<label>Product Name</label>
<input type="text" class="form-control" id="productName" name="productName" placeholder="Enter Product Name" value="<?php echo $row['productName'] ?>" /><span class="error"> <?php echo $nameError;?></span>
</div>
<div class="form-group">
<label>Quantity</label>
<input type="Number" class="form-control" id="QTY" name="QTY" placeholder="Enter Quantity" value="<?php echo $row['QTY'] ?>" min='1' max='100' >
</div>
<div class="form-group">
<label>Price</label>
<input type="text" class="form-control" id="productPrice" name="productPrice" placeholder="Enter Price" value="<?php echo $row['productPrice'] ?>" required/>
</div>
<div class="form-group">
<label>Variable</label>
<input type="text" class="form-control" id="Variable" name="Variable" placeholder="Enter Variable" value="<?php echo $row['Variable'] ?>" required>
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" id="productDescription" name="productDescription" /><?php echo $row['productDescription'] ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Update Item</button>
</form>
<?php
endforeach;
}
$nameError ="";
if(isset($_POST['submit'])){
if (empty($_POST["productName"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["productName"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
$productID = $_GET['id'];
$productName = $_POST['productName'];
$productDescription = $_POST['productDescription'];
$productPrice = $_POST['productPrice'];
$QTY = $_POST['QTY'];
$Variable = $_POST['Variable'];
global $conn;
$sql = "UPDATE product SET productName = :productName, productDescription = :productDescription, productPrice = :productPrice, QTY = :QTY, Variable = :Variable WHERE productID = :productID";
$statement = $conn->prepare($sql);
$statement->bindValue(':productName', $productName);
$statement->bindValue(':productDescription', $productDescription);
$statement->bindValue(':productPrice', $productPrice);
$statement->bindValue(':productID', $productID);
$statement->bindValue(':QTY', $QTY);
$statement->bindValue(':Variable', $Variable);
$result = $statement->execute();
$statement->closeCursor();
header("location: ../view/success.php");
return $result;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
}
?>
Inside your form put this code:
<input type="hidden" value="<?php echo $productID ?>" name="id" />
This will submit the hidden field. PHP wrote your $productID to it and it get submitted as part of the $_POST[]
<form action="process.php<?php echo"?id=$productID" ?> " method="post">
is totally fine.. access the productID with
$_GET['id']
<?php
//include 'includes/connectie.php';
if (isset($_GET['id'])){
$product_id=$_GET['id'];
} else {
$product_id=$_POST['id'];
}
$user = 'userID';
$pass = 'mypassword';
$dbh = new PDO( 'mysql:host=localhost;dbname=webshop', $user, $pass );
$sql = "SELECT * FROM `producten` WHERE product_id='$product_id'";
$sql_result = $dbh->query($sql);
foreach($sql_result as $row)
{
$prijs=$row['prijs'];
$product_naam=$row['product_naam'];
$product_categorie=$row['product_categorie'];
$product_specificaties=$row['product_specificaties'];
$foto=$row['foto'];
$product_id=$row['product_id'];
$product_soort=$row['product_soort'];
echo "Product id nummer:", $product_id;
}
//$_SESSION['prijs'] = $prijs;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//if (!empty($product_naam) && !empty($product_specifcaties) && !empty($product_categorie) && !empty($prijs)
//&& !empty($product_soort))
If (isset($_POST['submit']))
{
$sql = "UPDATE producten
SET prijs='$prijs', product_naam='$product_naam', product_specificaties='$product_specificaties',
product_categorie='$product_categorie', product_soort='$product_soort',
WHERE product_id='$product_id'";
$query = $dbh->prepare( $sql );
$result = $query->execute();
if ($result){
echo "Product aangepast!!!!! in id:";
echo $product_id;
} else {
echo "Product NIET aangepast!!!!";
}
}
}
?>
<form name="admin" action="producten_echt_aanpassen.php" method="POST" enctype="multipart/form-data">
<p>
<label for 'product_id'>Product ID: </label><br>
<input type="text" name="id" value="<?php print $product_id; ?>"/>
</p>
<p>
<label for 'product_naam'>Naam: </label><br>
<input type="text" name="product_naam" value="<?php print $product_naam; ?>"/>
</p>
<p> <label for 'product_specificaties'>Specificaties: </label><br>
<textarea rows= "4" cols="50" name="product_specificaties"><?php print $product_specificaties; ?>
</textarea>
</p>
<p>
<label for 'prijs'>Prijs: </label><br>
<input type="text" name="prijs" value="<?php print $prijs; ?>"/>
</p>
<p>
<label for 'product_categorie'>Iphone: </label><br>
<input type="text" name="product_categorie" value="<?php print $product_categorie; ?>"/>
</p>
<p>
<label for 'product_soort'>Soort: </label><br>
<input type="text" name="product_soort" value="<?php print $product_soort; ?>"/>
</p>
<br/>
<label for 'uploadfile'>Kies foto <img src="<?php print $foto; ?>"></label><br>
<input type="file" name="file" ><br><br>
<input type="submit" name="submit" value="Submit">
</form>
I have a form in which I load properties of products like the product name, price, photo etc. The properties are then possible to change and then updated in the database. But the sql update statement does not execute. Can anybody help me out?
there is a , before the where on the update that should not be there. Try to activate error reporting like this: How to get useful error messages in PHP? so that you know wwhy things are failing
I have the form that is for users to edit their profiles:
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Edit Admin: <?php echo htmlentities($admin["username"]); ?></h2>
<form action="edit_admin.php?usr_serno=<?php echo urlencode($admin["usr_serno"]); ?>" method="post">
<p>Username:
<input type="text" name="username" value="<?php echo htmlentities($admin["username"]); ?>" />
</p>
<p>Password:
<input type="password" name="password" value="" />
<?php if (!isset($_GET["password"])
</p>
<p>Email:
<input type="text" name="email" value="<?php echo htmlentities($admin["email"]); ?>" />
</p>
<p>Role:
<select type="int" name="role_serno">
<option value="1">Administrator</option>
<option value="2">User</option>
</select>
</p>
<p>First Name:
<input type="text" name="name" value="<?php echo htmlentities($admin["name"]); ?>" />
</p>
<p>Last Name:
<input type="text" name="lastname" value="<?php echo htmlentities($admin["lastname"]); ?>" />
</p>
<p>ID:
<input type="text" name="id" value="<?php echo htmlentities($admin["id"]); ?>" />
</p>
<p>Address:
<input type="text" name="address" value="<?php echo htmlentities($admin["address"]); ?>" />
</p>
<p>Postcode:
<input type="text" name="postcode" value="<?php echo htmlentities($admin["postcode"]); ?>" />
</p>
<p>City:
<select id="city" type="text" name="city" value="<?php echo htmlentities($admin["city"]); ?>">
<option value="Nicosia">Nicosia</option>
<option value="Limassol">Limassol</option>
<option value="Larnaca">Larnaca</option>
<option value="Paphos">Paphos</option>
<option value="Other">Other</option>
</select>
<input id="other_city" type="text" name="other_city" value="<?php echo htmlentities($admin["city"]); ?>" />
</p>
<p>Telephone:
<input type="text" name="telephone" value="<?php echo htmlentities($admin["telephone"]); ?>" />
</p>
<p>College:
<input type="text" name="college" value="<?php echo htmlentities($admin["college"]); ?>" />
</p>
<input type="submit" name="submit" value="Edit Admin" />
</form>
<br />
Cancel
</div>
`
And on top of that page i am checking and trying to update the users profile:
if (isset($_POST["submit"])) {
$required_fields = array("username","email","role_serno",
"name","lastname","id","telephone","address","college","postcode","city");
validate_presences($required_fields);
$fields_with_max_lengths = array("username" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// Perform Update
//if (!isset ($_POST["password"]))
//$hashed_password = $_GET["password"];
//if (isset ($_POST["password"]))
$id_serno = $admin["usr_serno"];
$username = mysql_prep($_POST["username"]);
$hashed_password = password_encrypt($_POST["password"]);
$email=mysql_prep($_POST["email"]);
$role_serno=mysql_prep($_POST["role_serno"]);
$name=mysql_prep($_POST["name"]);
$lastname=mysql_prep($_POST["lastname"]);
$id=mysql_prep( $_POST["id"]);
$date_create=mysql_prep( $_POST["date_create"]);
$address=mysql_prep( $_POST["address"]);
$postcode=mysql_prep( $_POST["postcode"]);
$city=mysql_prep( $_POST["city"]);
$telephone=mysql_prep( $_POST["telephone"]);
$college=mysql_prep( $_POST["college"]);
$query = "UPDATE users SET ";
$query .= "username = '{$username}', ";
$query .= "password = '{$hashed_password}', ";
$query .= "email = '{$email}', ";
$query .= "role_serno = '{$role_serno}', ";
$query .= "name = '{$name}', ";
$query .= "lastname = '{$lastname}', ";
$query .= "id = '{$id}', ";
$query .= "address = '{$address}', ";
$query .= "postcode = '{$postcode}', ";
$query .= "city = '{$city}', ";
$query .= "telephone = '{$telephone}', ";
$query .= "college = '{$college}' ";
$query .= "WHERE usr_serno = {$id_serno} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Admin updated.";
redirect_to("manage_admins.php");
} else {
// Failure
$_SESSION["message"] = "Admin update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (is set($_POST["submit"]))`
the issue comes when the user is posting a form without passing the password in cause then the database is updated with empty password and i have a check not to accept empty passwords at lo-gin page.
Is there a way to avoid and check this.
Please advise cause I am new with developing in php and I am not 100% sure how this is going to be done.
I tried so far to check if post value is empty then pass the current database value without encoding it.. but for some reason the if check doesn't actually do anything
you can check like this
if (isset($_POST["submit"]) && trim($_POST['password']) !="") {
//run the code
}else{
}
You can add a client side javascript validation here.
In case of server side
check
if(empty($_POST['password']))
{
// whatever you want to ask and do
}