I am using Unique Key for the field 'name', but when I update the record using edit file through admin, it gives me an error for duplicate entry. I can't remove unique key, it's required..
<!--update process-->
<?php
if(isset($_POST['submit']) and !empty($_POST['token'])){
print_r($_POST);
$name = $_POST['name'];
$size = $_POST['size'];
$linkt = $_POST['link'];
$seeds = $_POST['seeds'];
$leechs = $_POST['leechs'];
$active = $_POST['active'];
$query = "UPDATE tplus_torrentlist SET name = '$name', size = '$size', link = '$linkt', seeds = '$seeds', leechs = '$leechs', active = '$active'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$error = mysqli_error($link);
if(empty($error)){
$_SESSION['flash'] = '<blockquote style="background: green; color: #fff">One record updated</blockquote>';
header('location:dashbord.php');
}
else{
$_SESSION['flash'] = '<blockquote style="background: green; color: #fff">Sorry cant updated this record</blockquote>';
header('location:dashbord.php');
}
}
?>
<!--fetch values from database according to id-->
<?php
$sql = "SELECT * FROM tplus_torrentlist WHERE id = $id limit 1";
$result = mysqli_query($link ,$sql) or die(mysqli_error($link));
$row = $result->fetch_array();
?>
<div class="container">
<div class="row clearfix">
<div class="col-md-8 col-md-offset-2">
<?php if(!empty($response)){echo $response;} ?>
<h3>Edit this torrent</h3>
<hr/>
<form role="form" class="form" action="edit.php?id=<?php echo $_GET['id']?>" method="POST">
<label>Name</label>
<input type="text" name="name" value="<?php echo $row['name']?>" class="form-control input-sm">
<label>Size</label>
<input type="text" name="size" value="<?php echo $row['size']?>" class="form-control input-sm">
<label>Link</label>
<input type="text" name="link" value="<?php echo $row['link']?>" class="form-control input-sm">
<label>Seeds</label>
<input type="text" name="seeds" value="<?php echo $row['seeds']?>" class="form-control input-sm">
<label>Leechs</label>
<input type="text" name="leechs" value="<?php echo $row['leechs']?>" class="form-control input-sm">
<label>Active</label>
<select name="active" class="form-control input-sm">
<?php if($row['active'] ==0){?>
<option value="0">Active</option>
<option value="1">InActive</option>
<?php }else{ ?>
<option value="1">InActive</option>
<option value="0">Active</option>
<?php } ?>
</select>
<br/>
<input type="hidden" name="token" value="<?php echo rand(100, 100000)?>">
<input type="submit" name="submit" value="update torrent" class="btn btn-info">
</form>
</div>
</div>
</div>
Any solution without removing unique key from the field 'name' ?
Your update query need to correct as following -
$query = "UPDATE tplus_torrentlist SET name = '$name', size = '$size', link = '$linkt', seeds = '$seeds', leechs = '$leechs', active = '$active' WHERE id = $id limit 1";
Related
When checking my nonce, the hidden input values ($form_action, $timestamp, and $form_hash) are returning as blank instead of returning as equal the nonce variables ($action, $time, and $hash). This is preventing my if statement from running and my form data from submitting to the database. If I directly set the respective variables as equal the code runs great and the data is inserted into the database so I am pretty sure the problem is coming from the PHP code that is inserted as the value for the hidden inputs. Does anyone know why this is returning as blank?
HTML Code
<!DOCTYPE html>
<html>
<body>
<h1>Tournament Registration</h1>
<hr style=
"background-color:black;
margin:auto;">
<form
action="/Forms/connection.php"
method="post">
<input
type = "hidden"
name = "timestamp"
value ="<?php echo $time; ?>">
<input
type = "hidden"
name = "form_action"
value = "<?php echo $action; ?>">
<input
type = "hidden"
name = "form_hash"
value = "<?php echo $hash; ?>">
<div
class="form-field">
<input
style=
"width:250px;
padding:10px;
margin-top: 20px;"
type="text"
class="text"
name="firstname"
placeholder="First Name"
required>
<br>
<br>
</div>
<div
class="form-field">
<input
style=
"width:250px;
padding:10px;"
type="text"
class="text"
name="lastname"
placeholder="Last Name"
required>
<br>
<br>
</div>
<div
class="form-field">
<input
style=
"width:250px;
padding:10px;"
type="email"
class="text"
name="email"
placeholder="Email"
required>
<br>
<br>
</div>
<div
class="form-field">
<input
style=
"width:250px;
padding:10px;"
type="text"
class="text"
name="phonenumber"
placeholder="Phone Number"
required>
<br>
<br>
</div>
<div
class="form-field">
<input
style=
"width:250px;
padding:10px;"
type="text"
class="text"
name="handicap"
placeholder="Handicap"
required>
<br>
<br>
</div>
<div
class="form-field">
<select
style=
"width:250px;
padding:10px;"
class="text"
name="shirtsize"
size = 1
required>
<option
value=""
selected>
Shirt Size
</option>
<option
value="S">
S
</option>
<option
value="M">
M
</option>
<option
value="L">
L
</option>
<option
value="XL">
XL
</option>
<option
value="2XL">
2XL
</option>
<option
value="3XL">
3XL
</option>
</select>
</div>
<br>
<div
class="form-field">
<input
style=
"width:250px;
padding:10px;
margin-left:auto;"
type="submit"
value="Register">
</div>
</form>
</body>
</html>
PHP Code
<?php
require_once('config.php');
//Nonce
$time = time();
$action = 'tournament_registration';
$str = sprintf('%s_%s_%s', $action, $time, $NONCE_SALT);
$hash = hash('sha512', $str);
if (! empty($_POST)){
// Extract Post Data
extract($_POST);
$timestamp = $_POST['timestamp'];
$form_action = $_POST['form_action'];
$form_hash = $_POST['form_hash'];
echo "timestamp = "; print_r($timestamp);
echo '<br/>';
echo "form_action = "; print_r($form_action);
echo '<br/>';
echo "form_hash = "; print_r($form_hash);
echo '<br/>';
echo "firstname = "; print_r($firstname);
echo '<br/>';
echo "lastname = "; print_r($lastname);
echo '<br/>';
echo "email = "; print_r($email);
echo '<br/>';
echo "phonenumber = "; print_r($phonenumber);
echo '<br/>';
echo "handicap = "; print_r($handicap);
echo '<br/>';
echo "shirtsize = "; print_r($shirtsize);
echo '<br/>';
// Check Nonce
$calc_str = sprintf('%s_%s_%s', $form_action, $timestamp, $NONCE_SALT);
$calc_hash = hash('sha512', $calc_str);
if($calc_hash == $form_hash){
$filter_firstname = filter_var($firstname, FILTER_SANITIZE_STRING);
$filter_lastname = filter_var($lastname, FILTER_SANITIZE_STRING);
$filter_email = filter_var($email, FILTER_VALIDATE_EMAIL);
$filter_phonenumber = filter_var($phonenumber, FILTER_SANITIZE_STRING);
$filter_handicap = filter_var($handicap, FILTER_SANITIZE_STRING);
$filter_shirtsize = filter_var($shirtsize, FILTER_SANITIZE_STRING);
}
if ($filter_email != false){
//Send to database
$mysql = new mysqli($servername, $username, $password, $database);
$stmt = $mysql->prepare("INSERT INTO Registration (firstname, lastname, email, phonenumber, handicap, shirtsize) VALUES (?,?,?,?,?,?)");
$stmt->bind_param('ssssss', $filter_firstname, $filter_lastname, $filter_email, $filter_phonenumber, $filter_handicap, $filter_shirtsize);
$insert = $stmt->execute();
//Close Connection
$stmt->close();
$mysql->close();
}
else {
$insert = false;
}
}
else {
$insert = false;
}
?>
<form method="post">
<div class="form-group">
<label >Product</label>
<select class="form-control" name="product" id="supplier-select" >
<option value="">Select a Product </option>
<?php
$link = mysqli_connect();
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
$query="select id,name from product";
$result = mysqli_query($link,$query);
while($row = mysqli_fetch_array($result)){
echo "<option value=".$row['id']."name='product' >".$row['name']."</option>";
}
?></select>
</div>
<div class="form-group">
<label >Date</label>
<input type="date" name="date" class="form-control" id="" >
</div>
<div class="form-group">
<label >Sale Quantity</label>
<input type="text" name="quantity" class="form-control" id="">
</div>
<div class="form-group">
<label >Sale Price</label>
<input type="text" name="price" class="form-control" id="">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
$product = $row['product'];
$date =$_POST['date'];
$quan = $_POST['quantity'];
$price = $_POST['price'];
$link= mysqli_connect();
if(!$link){
die ('connection unsuccessful'. mysqli_connect_error($link));
}
$sql = "INSERT INTO items_sale (sale_id, prod_id, date, sale_quantity, sale_price) VALUES ('$id','$product','$date','$quan','$price')";
if (mysqli_query($link, $sql)) {
exit();
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
how do I pass in value from selected option from to insert query in this code here. i have using row[] but the value is not passing on in the from to my insert query when I selected. in past i have tried POST['id'] but it select the same value as the id before.
Try changing line
echo "<option value=".$row['id']."name='product' >".$row['name']."</option>";
to
echo "<option value=".$row['id'].">".$row['name']."</option>"
$row['product'] doesn't exist - try changing the beginning of your php code to
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
$product = $_POST['product'];
...
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']
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">