I've looked at this code until I'm cross-eyed and can't see the error I'm making. I'm a bit of a beginner.
My HTML - editPost.php:
<?php
session_start();
include "includes/header.php";
include "connectioninfo.php";
include "functions.php";
if(isset($_SESSION['user']))
{
editPost();
}
else
{
header("Location: /");
}
$return = getPost();
?>
<div class="container">
<form action="editPost.php" method="post">
<?php $id = $_GET['id']?>
<input type="hidden" name="id" value="<?php echo $id?>">
<div class="row">
<div class="lab">
<label for="category">Category:<br/></label>
</div>
<div class="inp">
<select id="category" required autofocus name="category">
<option value="" selected disabled hidden>Choose a category.</option>
<option value="Something">About</option>
<option value="Something else">Coding</option>
</select>
</div>
</div>
<div class="row">
<div class="lab">
<label for="title">Title.</label>
</div>
<div class="inp">
<input type="text" name="title" placeholder="Title" required value="<?php echo $return[0]?>">
</div>
</div>
<div class="row">
<div class="lab">
<label for="content">Content.</label>
</div>
<div class="inp">
<textarea name="content" id="content" style="height: 30em;"><?php echo $return[1]?></textarea>
</div>
</div>
<div class="row">
<input type="submit" name="submit" value="Post.">
</div>
</form>
</div>
<?php
include "includes/footer.php";
?>
getPost() is just getting the values to autofill the form. it's a function in the included functions.php:
function getPost()
{
global $connection;
$id=$_GET['id'];
$query = "SELECT * FROM database WHERE id = '$id'";
$result = $connection->query($query);
if($result)
{
while($post = $result->fetch_object())
{
$id = $post->id;
$title = $post->title;
$link = $post->permalink;
$summary = $post->summary;
$category = $post->category;
$content = $post->content;
$pubDate = $post->pubDate;
$author = $post->author;
$return = array($title,$content);
return $return;
}
}
else
{
die('Query FAILED!' . mysqli_error());
}
}
and finally, editPost()
function editPost()
{
global $connection;
if(isset($_POST['submit']))
{
global $connection;
$title = mysqli_real_escape_string($connection,$_POST['title']);
$content = mysqli_real_escape_string($connection,$_POST['content']);
$category = $_POST['category'];
$id = $_POST['id'];
//Permalink
$link = strtolower(trim($title));
$link = preg_replace('/[^a-z0-9-]/', '-', $link);
$link = preg_replace('/-+/', "-", $link);
$link = rtrim($link, '-');
$link = preg_replace('/\s+/', '-', $link);
$query = "UPDATE database SET title = '$title', permalink = '$link', content = '$content', category = '$category' ";
$query .= "WHERE id = '$id'";
$result = $connection->query($query);
if(!$result)
{
die('Query FAILED!' . mysqli_error());
}
else
{
header("Location: /");
}
$result->close();
}
}
Clicking on the edit link of a post brings me to this form, and it looks great - title and content are filled out with what's in the database, and I'm ready to edit.
The process (both html and function) is nearly identical to my createPost.php, and that works fine. but editPost.php just sends me back to the same page, with no values in the fields, and the post hasn't been updated. No error messages either.
What am I missing?
Edit
As a reference, I'm posting the contents of newPost.php and the function newPost() - which are working fine.
newPost.php:
<?php
session_start();
include "connectioninfo.php";
include "functions.php";
if(isset($_SESSION['user']))
{
newPost();
}
else
{
header("Location: /");
}
include "includes/header.php";
?>
<div class="container">
<form action="newPost.php" method="post">
<div class="row">
<div class="lab">
<label for="category">Category.</label>
</div>
<div class="inp">
<select id="category" required autofocus name="category">
<option value="" selected disabled hidden>Choose a category.</option>
<option value="About">About</option>
<option value="Coding">Coding</option>
</select>
</div>
</div>
<div class="row">
<div class ="lab">
<label for="title">Title.</label>
</div>
<div class ="inp">
<input type="text" name="title" required placeholder="Title">
</div>
</div>
<div class="row">
<div class ="lab">
<label for="summary">Summary.</label>
</div>
<div class ="inp">
<input type="text" name="summary" required placeholder="Summary (for the RSS feed and Twitter)">
</div>
</div>
<div class="row">
<div class="lab">
<label for="content">Content.</label>
</div>
<div class="inp">
<textarea name="content" id="content" placeholder="The content of the post" style="height: 30em;"></textarea>
</div>
</div>
<div class="row">
<input type="submit" name="submit" value="Post.">
</div>
</form>
</div>
<?php
include "includes/footer.php";
?>
newPost():
function newPost()
{
if(isset($_POST['submit']))
{
global $connection;
$title = mysqli_real_escape_string($connection,$_POST['title']);
$summary = mysqli_real_escape_string($connection,$_POST['summary']);
$content = mysqli_real_escape_string($connection,$_POST['content']);
$category = $_POST['category'];
$pubDate = date("Y-m-d H:i:s");
$author = $_SESSION['user'];
//Permalink
$link = strtolower(trim($title));
$link = preg_replace('/[^a-z0-9-]/', '-', $link);
$link = preg_replace('/-+/', "-", $link);
$link = rtrim($link, '-');
$link = preg_replace('/\s+/', '-', $link);
$query = "INSERT INTO database(title, permalink, category, summary, content, pubDate, author) ";
$query .= "VALUES ('$title', '$link', '$category', '$summary', '$content', '$pubDate', '$author')";
$result = $connection->query($query);
if(!$result)
{
die('Query FAILED!' . mysqli_error());
}
else
{
header("Location: /");
}
$result->close();
}
}
thanks to everyone for their help. As I found out and stated in the comments, the problem was in my .htaccess
I do a rewrite in .htaccess - mysite.com/editPost.php?id=1 is actually mysite.com/edit/1 - running the long form WORKS, the short form is giving me the error.
My .htaccess has RewriteRule ^edit/([^/.]+)?$ /editPost?id=$1 [L] I just had to change <form action="editPost.php" method="post"> in editPost.php to <form action="edit" method="post"> and it works no problem :-/
Related
I can update image on my application but if I have to update same picture again and again when I click edit button on edit section...so I want to remain current image when I update edit section without any change for image.
I tried to put these codes below but it didn't work....
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
Does anyone give some advise or concern for my codes?
I really appreciate!
Thank you!
<!-- Edit -->
<?php
if(isset($_REQUEST['edit_post_id'])){
$the_post_id = $_REQUEST['edit_post_id'];
$posted = $db->prepare("SELECT * FROM posts WHERE post_id = $the_post_id ");
$posted->execute(array($the_post_id));
$posted_p = $posted->fetch();
}
?>
<?php
if(isset($_POST['edit_post'])){
$edit_posts = $db->prepare("UPDATE posts SET post_image=?, post_contents=? WHERE post_id ='{$the_post_id}' ");
$edit_posts->execute(array(
$image = date('YmdHis') . $_FILES['image']['name'],
$_POST['post_contents']
));
move_uploaded_file($_FILES['image']['tmp_name'], './images/' . $image);
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
header('Location: index.php');
exit();
}
?>
<!-- Edit form -->
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="well">
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="summernote">Edit</label>
<textarea class="form-control" name="post_contents" id="summernote" col="30" rows="10"><?php echo htmlspecialchars($posted_p['post_contents'], ENT_QUOTES); ?></textarea>
</div>
<div class="form-group">
<label for="post_image">Image</label>
<input type="file" name="image" >
<img width="100" src="./images/<?php echo $posted_p['post_image']; ?>" >
</div>
<span class="form-group">
<p><input class="btn btn-primary" type="submit" name="edit_post" value="Edit"></p>
</span>
</form>
</div>
</div>
</div>
</div>
you should update your query so it sets post_image only if $_FILES['image'] it exists
this should work:
<?php
if(isset($_POST['edit_post'])){
$image = $_FILES['image'] ? date('YmdHis') . $_FILES['image']['name'] : "";
$edit_posts = $db->prepare(
"UPDATE posts SET post_contents=?". empty($image) ?: ", post_image=?" ."WHERE post_id ='{$the_post_id}' "
);
$params = array(
$_POST['post_contents']
);
if (!empty($image)) {
$params[] = $image;
}
$edit_posts->execute($params);
move_uploaded_file($_FILES['image']['tmp_name'], './images/' . $image);
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
header('Location: index.php');
exit();
}
?>
As i am newbie to PHP kindly pardon me if i looks silly ,
I created a form in php , while i do the update part of the form the update reflects in db whereas in the form it still shows the same old value . i tried refresh and force refresh but nothing changes .
Whereas if i logout and login again , the form shows the updated value .
I tried using die(); after mysql_close($link); but it logs out the session and needs to re-login .
Kindly help me on viewing the changes while i am still inside the login .
My code is as follows :
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($link);
}else {
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?>
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo "$name"; ?></h3>
<h5 class="widget-user-desc"><?php echo "$role"; ?></h5>
</div>
<div class="box-footer no-padding">
<form role="form" method = "post" action = "<?php $_PHP_SELF ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo "$name"; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo "$email"; ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo "$password"; ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php
}
?>
SOLUTION
1) use the updated value like $name_a instead of $name because $name_a contain updated value and $name contain old value
2) reload page after update and get new value from database on page load and store that value in $name , $email etc variable (if new data update successfully in database then only you get new value )
3) if You store your data in session or cookie then update session and cookie value also when you update in database
Try this:
<?php
$name = '';
$email = '';
$password = '';
$update_id = '';
//$img = '';
//$role = '';
//$link = null;
if(
isset($_POST['update']) &&
isset($_POST['id']) &&
isset($_POST['name']) &&
isset($_POST['email']) &&
isset($_POST['password'])
) {
$update_id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$sql = 'UPDATE admin SET a_name = \'' . $name . '\', a_email = \'' . $email . '\', password = \'' . $password . '\' WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if(!$result)
die('Could not update data: ' . mysql_error($link));
echo 'Updated data successfully', "\n";
}
elseif(isset($_GET['id'][0])) {
$update_id = mysql_real_escape_string($_GET['id']);
$sql = 'SELECT a_name,a_email,a_password FROM admin WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if($result) {
$result = mysql_fetch_row($result);
$name = $result[0];
$email = $result[1];
$password = $result[2];
}
else {
echo 'Could not find the id.' . "\n";
$update_id = '';
}
}
unset($result);
if(isset($update_id[0])) {
mysql_close($link);
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<img src="<?php echo htmlspecialchars($img); ?>" class="img-circle" alt="User Image">
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo htmlspecialchars($name); ?></h3>
<h5 class="widget-user-desc"><?php echo htmlspecialchars($role); ?></h5>
</div>
<div class="box-footer no-padding">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($update_id); ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo htmlspecialchars($name); ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo htmlspecialchars($email); ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo htmlspecialchars($password); ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php }
else {
$sql = 'SELECT aid,a_name FROM admin';
$result = #mysql_query($sql, $link);
if($result) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '' . $row['a_name'] . '<br />' . "\n";
}
}
mysql_close($link);
}
?>
As #DivyeshSavaliya mentioned in the comment the issue is ,
I didn't Used Select query after update . Once done that the issue solved
The new working code is
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
}
$result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link);
while($row = mysql_fetch_array($result)){
$name = $row['a_name'];
$email = $row['a_email'];
$password = $row['password'];
}
mysql_close($link);
?>
Thanks to #DivyeshSavaliya
I Have a profile page and admin can edit profile users,
all process on one page done,How i can refresh and update value form data after success query update ?
User.class file :
class User {
...
public function updateUser($id, $firstname, $lastname, $phone, $birthday, $managerid)
{
$con = $this->DBconnect();
$id = (int)$id;
$managerid = $this->checkParam($managerid);
$firstname = $firstname;
$lastname = $lastname;;
$mobile = $phone;
$birthday = $this->checkParam($birthday);
$query = "UPDATE `users` SET `manager_id` = :manager_id,`firstname` = :firstname,`lastname` = :lastname,`birthday` = :birthday,`mobile` = :mobile WHERE `id` = :id";
$result = $con->prepare($query);
$result->BindParam(':id', $id, PDO::PARAM_INT);
$result->BindParam(':manager_id', $managerid, PDO::PARAM_INT);
$result->BindParam(':firstname', $firstname);
$result->BindParam(':lastname', $lastname);
$result->BindParam(':birthday', $birthday);
$result->BindParam(':mobile', $mobile);
$check = $result->execute();
return true;
}}
profile.php file :
<?php
if (isset($_GET['id'])) {
$id = (int)$_GET['id'];
}
$user = new User();
$user_info = $user->getuser($id);
while ($info = $user_info->fetch(PDO::FETCH_ASSOC)) {
$firstname = $info['firstname'];
$lastname = $info['lastname'];
$mobile = $info['mobile'];
$birthday = $info['birthday'];
$managerid = $info['manager_id'];
}
$manager_ob = new Manager();
$managers = $manager_ob->getAllManager();
$managers_name = array();
while ($manager = $managers->fetch(PDO::FETCH_ASSOC)) {
$managers_list[] = $manager;
}
if (isset($_POST['edit-profile'])) {
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
}
?>
<form method="post" action="#" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">ID</label>
<div class="col-sm-10"><input type="text" readonly class="form-control" name="user_id" id="user_id" value="<?php echo check_param($id); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_firstname" value="<?php echo check_param($firstname); ?>" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_lastname" value="<?php echo check_param($lastname); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_mobile" value="<?php echo check_param($mobile); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label" for="birthday">Birthday
</label>
<div class="col-sm-10"><input id="birthday" type="text" class="form-control" name="user_birthday"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Manager</label>
<div class="col-sm-10"><select class="form-control m-b" name="manager_id">
<?php foreach ($managers_list as $managers_n) { ?>
<option <?php if ($managers_n['id'] == $managerid) {
echo 'selected';
} ?>
value="<?php echo $managers_n['id']; ?>"> <?php echo $managers_n['name']; ?></option>;
<?php }
?>
</select>
</div>
</div>
<input type="submit" name="edit-profile" class="btn btn-block btn-w-m btn-success"
value="Edit profile">
</form>
i load profile data after submit edit :
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
only display message Profile Edited but must be refresh page for renew data
I must fetch again query for update values? or have better way ?
I suggest you use Ajax for this this is probably the best way to change the data without refreshing. More info about (jQuery) ajax http://api.jquery.com/jquery.ajax/
Your other option is to force a refresh after the submit. You can do this in PHP like so:
Header('Location: '.$_SERVER['PHP_SELF']);
I would suggest choosing ajax to tackle this problem though.
Good luck :)
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'];
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'];