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";
}
}
?>
Related
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 trying to add an 'edit' button on my database table output, it captures the information correctly from the previous screen, however when I press the 'update' button, the values just revert back to what they came in as, and nothing is updated on the database. Does anyone have any idea what could be the matter?
<?php
session_start();
error_reporting(E_ALL);
include('connect.php');
if ($_SESSION['role']!='Admin') {
header('Location: index.php');
exit;
}
if(isset($_GET['edit_id'])) {
$sql = "SELECT * FROM products WHERE product_id =".$_GET['edit_id'];
$result = mysqli_query($connection, $sql);
$row = mysqli_fetch_array($result);
}
if(isset($_POST['btn-update'])){
$productID = $_POST['productID'];
$productName = $_POST['productName'];
$productDesc = $_POST['productDesc'];
$productType = $_POST['productType'];
$productPrice = $_POST['productPrice'];
$stockAmount = $_POST['stockAmount'];
$update = "UPDATE products SET product_id='$productID', name='$productName', description='$productDesc', type='$productType', price='$productPrice', stock_amount='$stockAmount' WHERE product_id=". $_GET['edit_id'];
$up = mysqli_query($connection, $update);
if(!isset($sql)){
die("$sql Error" .mysqli_connect_error());
} else {
header("location: manage-products.php");
}
} ?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<form method="post">
<h1>Edit Product Information:</h1>
Product ID:<br>
<input type="number" name="productID" value="<?php echo $row['product_id']; ?>"><br>
Product Name:<br>
<input type="text" name="productName" value="<?php echo $row['name']; ?>"><br>
Product Description:<br>
<input type="text" name="productDesc" value="<?php echo $row['description']; ?>"><br>
Product Type:<br>
<input type="radio" name="productType" value="book" checked> Book<br>
<input type="radio" name="productType" value="stationary"> Stationary<br>
<input type="radio" name="productType" value="gift"> Gift<br>
Product Price:<br>
<input type="number" min="1" step="any" name="productPrice" value="<?php echo $row['price']; ?>"><br>
Stock Amount:<br>
<input type="number" name="stockAmount" value="<?php echo $row['stock_amount']; ?>"><br><br>
<button type="submit" name=btn-update" id="btn-update" <strong>Update</strong></button>
<button type="button" value="button">Cancel</button>
</form>
</body>
</html>
i have this code for the user-edit.php
what i need with this code is to fetch user data from database and show it to the textbox and also the user able to edit the textbox value and updating the database
<?php
include("config/session.php");
include("config/connection.php");
$user_id = $_SESSION['LOGGED_USER_ID'];
?>
<?php
$sql_query = "SELECT * FROM table_users WHERE `SNo` = '$user_id'";
$query = mysql_query($sql_query);
//$i = 1;
$fetch = mysql_fetch_assoc($query);
//$user_id = $_GET['id'];
?>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<fieldset>
<p>
<label for="simple-input" >User Name</label>
<input type="text" id="UserName" class="round default-width-input" autofocus name="UserName" value="<?php echo $fetch['UserName'];?>" readonly="readonly" />
</p>
<p>
<label for="simple-input" >Password</label>
<input type="text" id="pass_word" class="round default-width-input" autofocus name="pass_word" value="<?php echo $fetch['pass_word'];?>" />
</p>
<p>
<label for="simple-input" >Email ID</label>
<input type="text" id="Email" class="round default-width-input" autofocus name="Email" value="<?php echo $fetch['Email'];?>" />
</p>
<p>
<label for="simple-input" >Website</label>
<input type="text" id="website" class="round default-width-input" autofocus name="website" value="<?php echo $fetch['website'];?>" />
</p>
</fieldset>
<input type="submit" class="btn btn-primary btn-large" name="form_submit" value="Update Data"/>
</form>
<?php
if(isset($_POST['form_submit']))
{
"UPDATE `table_users` SET `pass_word` = '".$_POST['pass_word']."',`Email` = '".$_POST['Email']."',`website` = '".$_POST['website']."', WHERE `SNo` = '$user_id'";
// sql query for update data into database
if(mysql_query($sql_query))
{
echo '<script type="text/javascript">';
echo 'alert("Data Are Updated Successfully");';
echo '</script>';
}
else
{
echo '<script type="text/javascript">';
echo 'alert("error occured while updating data");';
echo '</script>';
}
}
?>
</div>
</div>
</div>
been working with this for hours and still the data are not updated to the mysql database, been trying several way but still the textbox value cant update the database, please help
remove , before where in query
$sql_query="UPDATE `table_users` SET `pass_word` = '".$_POST['pass_word']."',`Email` = '".$_POST['Email']."',`website` = '".$_POST['website']."' WHERE `SNo` = '$user_id'";
store query in $sql_query because you not store update string into variable
without store in $sql_query you run sql query
if(mysql_query($sql_query)) so store update query in $sql_query
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">
<?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