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();
}
?>
Related
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 :-/
After user log into his profile I am showing his user profile. And there I let him to add his profile picture. After user add his profile picture I want to insert image path to the database.
database at the login-id, username, password, email
database after profile picture save - id, username,password,email,name1(where img path save)
Following code save the picture in the given folder but it does not save the image path in the database.can anybody help me please?
<?php include('header.php');?>
<?php include('config.php');?>
<?php
// index.php
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
$username = $_SESSION['username'];
$sql = "SELECT * FROM services WHERE user_name = '".$_SESSION['username']."'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<?php
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
//$query = "insert into services(name1) values('".$name."') where user_name = '".$_SESSION['username']."'";
$query = " UPDATE services SET name1='$name' where user_name = '".$_SESSION['username']."";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<div class="container">
<div class="row">
<div class="col-md-7 ">
<div class="panel panel-default">
<div class="panel-heading"> <center> <h4 >User Profile</h4></center></div>
<div class="panel-body">
<div class="box box-info">
<div class="box-body">
<div class="col-sm-6">
<div align="center">
<form method="post" action="welcome.php" enctype='multipart/form-data'>
<div class="imageupload panel panel-default">
<div class="file-tab panel-body">
<label class="btn btn-default btn-file">
<span>Browse</span>
<!-- The file is stored here. -->
<input type="file" name="file">
</label>
<button type="button" class="btn btn-default">Remove</button>
</div>
<input type='submit' value='Save name' name='but_upload'>
</div>
</div>
<br>
<!-- /input-group -->
</div>
<div class="col-sm-6">
<h4 style="color:#00b1b1;"><?php echo $row ['name']; ?></h4></span>
<span><p><?php echo $row ['service']; ?></p></span>
</div>
<div class="clearfix"></div>
<hr style="margin:5px 0 5px 0;">
Change
$query = " UPDATE services SET name1='$name' where user_name = '".$_SESSION['username']."";
to
$query = ("UPDATE services SET name1='$name' where user_name = '".$_SESSION['username']."") or die(mysqli_error($con));
I added mysqli_error. It will print errors in the query & brackets
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 am working on a CMS and seem to be having issues currently with my edit code and I can't figure out what the problem is for the life of me, when I submit to edit, everything goes through as if the edit was successful, however nothing is ever changed or submitted to the database.
I have been trying many different things and nothing seems to make any difference, I am totally lost on this one.
editarticle.php
<?php
ob_start();
session_start();
include_once('includes/connection.php');
include_once('includes/news.php');
include_once('includes/functions.php');
$article = new Article;
$funct = new UserFunctions;
if (isset($_SESSION['logged_in'])) {
$articles = $article->fetch_all();
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (empty($title) or empty($content)) {
$error = 'All fields are required!';
header('Location: index.php?p=editarticle');
} else {
global $pdo;
$query = $pdo->prepare('UPDATE articles SET article_title = ?, article_content = ? WHERE article_id=?');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $id);
$query->execute();
header('Location: index.php');
}
}
//check if an article is selected to be edited
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare("SELECT * FROM articles WHERE article_id = ?");
$query->bindValue(1, $id);
$query->execute();
$rows = $query->fetchAll();
//get the article title and content to put in edit inputs
foreach ($rows as $row) {
$id = $row['article_id'];
$title = $row['article_title'];
$content = $funct->br2nl($row['article_content']);
}
?>
<!-- POST -->
<div class="post">
<div class="topwrap">
<div class="userinfo pull-left">
<div class="avatar">
<img src="images/avatar.jpg" alt="" />
<div class="status green"> </div>
</div>
<div class="icons">
<img src="images/icon1.jpg" alt="" /><img src="images/icon4.jpg" alt="" /><img src="images/icon5.jpg" alt="" /><img src="images/icon6.jpg" alt="" />
</div>
</div>
<div class="posttext pull-left">
<h2>Edit Article</h2>
<!-- add Article form start !-->
<form action="editarticle.php" method="post" autocomplete="off">
<input type="text" name="title" value="<?php echo $title; ?>" /><br /><br />
<textarea rows="10" cols="87" name="content" /><?php echo $content; ?></textarea>
<!-- add article form break !-->
</div>
<div class="clearfix"></div>
</div>
<div class="postinfobot">
<div class="dateposted pull-right">
<!-- add article form continue !-->
<input class="btn btn-primary" type="submit" value="Submit Changes" />
</form>
<!-- add article form end !-->
</div>
<div class="clearfix"></div>
</div>
</div>
<!-- POST -->
<?php
} else {
?>
<!-- POST -->
<div class="post">
<div class="topwrap">
<div class="userinfo pull-left">
</div>
<div class="posttext pull-left">
<h2>Select an Article to Edit</h2>
<?php foreach ($articles as $article) { ?>
<?php echo $article['article_id']; ?> - <?php echo $article['article_title']; ?><br />
<?php } ?>
</div>
<div class="clearfix"></div>
</div>
<div class="postinfobot">
<div class="dateposted pull-right"> </div>
<div class="clearfix"></div>
</div>
</div>
<!-- POST -->
<?php
}
} else {
header('Location: index.php');
}
?>
includes/news.php
class Article {
public function fetch_all() {
global $pdo;
$article_status = 1;
$query = $pdo->prepare("SELECT * FROM articles WHERE article_status = ? ORDER BY article_timestamp DESC");
$query->bindValue(1, $article_status);
$query->execute();
return $query->fetchAll();
}
public function fetch_data($article_id) {
global $pdo;
$article_status = 1;
$query = $pdo->prepare("SELECT * FROM articles WHERE article_id = ? AND article_status = ?");
$query->bindValue(1, $article_id);
$query->bindValue(2, $article_status);
$query->execute();
return $query->fetch();
}
}
I am getting back into PHP for the first time in 10 years and have been doing a lot of C# development over the last 2 years. I am finding it very difficult to troubleshoot issues with PHP thus far, as I have gotten very little or no error messages to work with (not even in the error_log on my host).
Any ideas why this isn't submitting the changes to the database?
The page is seting $id with get when loaded. But then again you are posting the data to self by creating a new instance of post this new post doesn't know anything about $id
So you need to explicitly pass $id (unless it is a session variable, where you can use $_session variable to retrieve it) as a hidden value in your form
try adding this to form:
<input type="hidden" value="<?php echo $id;?>">
As #noob pointed out, yu need to pass the article id in the first form, because your UPDATE statement need it.
Therefore:
if (isset($_POST['title'], $_POST['content'], $_POST['id'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$id= $_POST['id'];
And in your form:
<form action="editarticle.php" method="post" autocomplete="off">
<input type="hidden" value="<?php echo $id;?>">
<input type="text" name="title" value="<?php echo $title; ?>" /><br /><br />
<textarea rows="10" cols="87" name="content" /><?php echo $content; ?></textarea>
<!-- add article form break !-->
</div>
<div class="clearfix"></div>
</div>
<div class="postinfobot">
<div class="dateposted pull-right">
<!-- add article form continue !-->
<input class="btn btn-primary" type="submit" value="Submit Changes" />
</form>
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'];