Updation not working using pdo in php - php

I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!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 Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></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="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>

This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];

Related

Togle to edit Mysql data from PHP

I have a table in my php where I show data from my 'users' table of mysql. In the table I added an edit button so that, if you click on the button, a form is shown below the table where you can edit some fields of the table's content, I have also added a delete button next to it to delete the row of the table you want, but that button works correctly.
The problem I have is with the edit button, which, when pressed, it doesn’t show me the form that I added below the table, but it takes me to the page 'registerTeacher.php?edit = 3' for example. Pressing the 'Edit' button, it should show the form to be able to edit but it doesn’t do anything, nor does it show me any errors. Can someone help me find where the problem is? Thank you.
This is my ‘indexAdmin.php’ code:
<?php
include('server.php');
include('Security.php');
include('Conexion.php');
include('registerTeacher.php');
?>
<?php
$style = "style='display:none;'";
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($conn, "SELECT * FROM users WHERE id=$id");
if (#count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$username = $n['username'];
$email = $n['email'];
$style = "style='display:block;'";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="styleIndexAdmin.css">
<meta charset="utf-8">
</head>
<body>
<!-- notification message -->
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'])) : ?>
<div class="navbar" id="navbar">
<a class="tablink" onclick="openPage('professorsRegistered', this, 'lightblue')" id="defaultOpen">Profesores</a>
</div>
<!----------- PROFESSROS REGISTERED TABLE ----------->
<div id="professorsRegistered" class="tabcontent"></br><br>
<table class="professorsRegistered">
<tr>
<th colspan="3"><h2>PROFESSORS REGISTERED</h2></th>
</tr>
<tr>
<th> Name </th>
<th> Edit </th>
<th> Delete </th>
</tr>
<?php
$result = $conn->query($sql);
$sql = "SELECT * FROM users WHERE rol='profesor'";
$result = $conn->query($sql);
if ($result->num_rows==0){
echo 'No professors';
}else{
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["username"]."</td>
<td><a href='registerTeacher.php?edit=".$row["id"]."' class='edit_btn' ><i class='fa fa-pencil-square-o' style='cursor:pointer;'></i></a></td>
<td><a class='eliminate' onClick=\"javascript: return confirm('Confirm to delete');\" href=\"deleteTeacher.php?id=".$row['id']."\">X</a></td>
</tr>";
}
}
?>
</table><br><br>
<!------- FORM TO EDIT REGISTERED TEACHERS ---------->
<form method="post" action="registerTeacher.php" <?php echo $style;?>>
<!----- newly added field--->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>USER</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>EMAIL</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<!--------BUTTON----->
<?php if ($update == true): ?>
<button class="btn_update" type="submit" name="update">EDIT</button>
<?php endif ?>
</div>
</form>
</div>
<?php endif ?>
<script>
function getUrlVars(){
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
vars[key] =value;
});
return vars;
}
function openPage(pageName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(pageName).style.display = "block";
elmnt.style.backgroundColor = color;
}
p = getUrlVars()["page"];
//alert(p);
if (p==undefined){
document.getElementById("defaultOpen").click();
}else{
openPage(p, this, 'lightblue');
}
</script>
</body>
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
</html>
This is my ‘registerTeacher.php’ file:
<?php
include('Conexion.php');
$username = "";
$email = "";
$errors = array();
$id = 0;
$update = false;
// UPDATE
if (isset($_POST['update'])) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
mysqli_query($conn, "UPDATE users SET username='$username', email='$email' WHERE id=$id");
$_SESSION['message'] = "User edited!";
header("Location: indexAdmin.php?page=professors");
}
?>
Because <a href=..> is used to redirect to some page in your case ,it is redirecting to registerTeacher.phppage as you have specify in your href attribute.Instead you can do like below :
When below <a href..> is clicked you can put form on registerTeacher.php like below :
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($conn, "SELECT * FROM users WHERE id=$id");
if (#count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$username = $n['username'];
$email = $n['email'];
$style = "style='display:block;'";
}
}
?>
<!------- FORM TO EDIT REGISTERED TEACHERS ---------->
<form method="post" action="abcpage.php" <?php echo $style;?>>
<!----- newly added field--->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>USER</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>EMAIL</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<!--------BUTTON----->
<?php if ($update == true): ?>
<button class="btn_update" type="submit" name="update">EDIT</button>
<?php endif ?>
</div>
</form>
Then you can passed this details to your action="abcpage.php".and write like below in that page i.e :
// UPDATE
if (isset($_POST['update'])) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
mysqli_query($conn, "UPDATE users SET username='$username', email='$email' WHERE id=$id");
$_SESSION['message'] = "User edited!";
header("Location: indexAdmin.php?page=professors");
}
?>
Hope this helps !
Note : Also try using prepared statement it is safe an secure.

The text of my web is garbled

I have used header("Content-Type:text/html; charset=utf-8"); & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> on both html & php parts.
But for the webpage contents displayed , the text of the Chinese words are garbled .How to tackle the problem ?
create.php
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=utf-8");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Amount = "";
$CName_err = $Address_err = $Amount_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_CName = trim($_POST["CName"]);
if(empty($input_CName)){
$CName_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z'-.\s ]+$/")))){
$CName_err = 'Please enter a valid name.';
} else{
$CName = $input_CName;
}
// Validate address
$input_Address = trim($_POST["Address"]);
if(empty($input_Address)){
$Address_err = 'Please enter an address.';
} else{
$Address = $input_Address;
}
// Validate Amount
$input_Amount = trim($_POST["Amount"]);
if(empty($input_Amount)){
$Amount_err = "Please enter the amount.";
} elseif(!ctype_digit($input_Amount)){
$Amount_err = 'Please enter a positive integer value.';
} else{
$Amount = $input_Amount;
}
// Check input errors before inserting in database
if(empty($CName_err) && empty($Address_err) && empty($Amount_err)){
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Amount) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName,$Address,$Amount));
Database::disconnect();
header("Location: index.php");
}}
?>
<!DOCTYPE html>
<!--<html lang="en">-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>捐贈表格</h2>
</div>
<p>本人願意以信用卡捐款</p><br>
<p>I would like to make donation</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($CName_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="CName" class="form-control" value="<?php echo $CName; ?>">
<span class="help-block"><?php echo $CName_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<textarea name="Address" class="form-control"><?php echo $Address; ?></textarea>
<span class="help-block"><?php echo $Address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?>">
<label>Amount</label>
<input type="text" name="Amount" class="form-control" value="<?php echo $Amount; ?>">
<span class="help-block"><?php echo $Amount_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
<p>多謝您的支持</p><br>
<p>Thank you for your support</p>
</div>
</div>
</div>
</div>
</body>
</html>
Update
garbled page :

PHP Not supporitng UTF-8? [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 7 years ago.
Hello i have been trying to make { View / edit / add Script }
which i got from google..
but the main issue is it's not supporting arabic language [UTF-8] encode
here is the code:
<?php
ini_set('default_charset', 'UTF-8');
setlocale(LC_ALL, 'UTF-8');
date_default_timezone_set('Asia/Riyadh');
error_reporting(0);
require 'database.php';
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$uidError = null;
$actionError = null;
$reasonError = null;
// keep track post values
$name = utf8_encode($_POST['Name']);
$uid = utf8_encode($_POST['uid']);
$action = utf8_encode($_POST['Action']);
$reason = utf8_encode($_POST['Reason']);
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($uid)) {
$uidError = 'Please enter UID';
$valid = false;
}
if (empty($action)) {
$actionError = 'Please enter action';
$valid = false;
}
if (empty($reason)) {
$reasonError = 'Please enter reason';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO clan187 (name,uid,action,reason) values(?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($name,$uid,$action,$reason,));
Database::disconnect();
header("Location: index.php");
}
}
?>
<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">
<br>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="Name" type="text" placeholder="Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($uidError)?'error':'';?>">
<label class="control-label">UID</label>
<div class="controls">
<input name="uid" type="text" placeholder="UUID" value="<?php echo !empty($uid)?$uid:'';?>">
<?php if (!empty($uidError)): ?>
<span class="help-inline"><?php echo $uidError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($actionError)?'error':'';?>">
<label class="control-label">Action</label>
<div class="controls">
<input name="Action" type="text" placeholder="Action" value="<?php echo !empty($action)?$action:'';?>">
<?php if (!empty($actionError)): ?>
<span class="help-inline"><?php echo $actionError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($reasonError)?'error':'';?>">
<label class="control-label">Reason</label>
<div class="controls">
<input name="Reason" type="text" placeholder="Reason" value="<?php echo !empty($reason)?$reason:'';?>">
<?php if (!empty($reasonError)): ?>
<span class="help-inline"><?php echo $reasonError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Well no idea why it's not working for me
any help will be great <3
You haven't said why it doesn't work. You may need to be more verbose.
Unless you specify it, forms are sent in the user's locale encoding. You need to set your form with an encoding. UTF-8 will allow characters from any region/language:
<form class="form-horizontal" action="create.php" method="post" accept-charset="UTF-8">
Now your $_POST[] elements will be already UTF-8 encoded, so you don't need to convert them. Change them to:
$name = $_POST['Name'];
$uid = $_POST['uid'];
$action = $_POST['Action'];
$reason = $_POST['Reason'];
Make sure the following is present in your file:
header('Content-type: text/html; charset=utf-8');
There's also a meta tag for in the document head.
meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
Make sure your data source/destination is collated for UTF-8.
Then the only other thing it could be is your text editor encoding. Should be UTF-8 without BOM. No matter what is going on in the file, if the file itself isn't UTF-8 then it won't work.

PHP Adding Data to Database

I've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far.
PHP CODE:
<?php
require 'database.php';
if ( !empty($_POST)) {
$iError = null;
$nError = null;
$dError = null;
$tError = null;
$id = $_POST['id'];
$name = $_POST['name'];
$Address = $_POST['Address'];
$phone = $_POST['phone'];
$valid = true;
if (empty($id)) {
$iError = 'add id';
$valid = false;
}
if (empty($name)) {
$nError = 'add name';
$valid = false;
}
if (empty($Address)) {
$dError = 'add address';
$valid = false;
}
if (empty($phone)) {
$tError = 'add phone';
$valid = false;
}
if ($valid) {
$tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)";
$arr1 = array($id, $name, $Address, $phone);
$stmt = sqlsrv_query($conn, $tsql, $arr1 );
if ( $stmt === FALSE ){
echo "New data created";
}
else {
echo "Error creating data";
die(print_r(sqlsrv_errors(),true));
}
}
}?>`
this is the HTML part:
<body>
<div>
<div>
<h3>CREAR</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class=" <?php echo !empty($iError)?'error':'';?>">
<label >ID</label>
<div >
<input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>">
<?php if (!empty($iError)): ?>
<span ><?php echo $iError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($nError)?'error':'';?>">
<label>name</label>
<div>
<input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nError)): ?>
<span><?php echo $nError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($emailError)?'error':'';?>">
<label >Address</label>
<div >
<input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>">
<?php if (!empty($dError)): ?>
<span><?php echo $dError;?></span>
<?php endif;?>
</div>
</div>
<div class=" <?php echo !empty($tError)?'error':'';?>">
<label >phoner</label>
<div >
<input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>">
<?php if (!empty($tError)): ?>
<span ><?php echo $tError;?></span>
<?php endif;?>
</div>
</div>
<div >
<button type="submit">Create</button>
Return
</div>
</form>
</div>
</div>

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