edit data from mysql db - php

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>

Related

Can't post image file into given directory with $_FILES function

I have two pretty much similar cases of adding image files to directory and they both work, but I don't know why this one doesn't, since it's done on the same principles.
And since it's not pasting into the "show" directory, the output is following:
add-album.php
<?php
include "config.php";
if (isset($_POST["submit_album"])) {
$album = $_POST["album_name"];
$album_prikazna = $_POST["album_prikazna"];
$photo = $_FILES["album_prikazna"]["album_name"];
$upload = "show/".$photo;
$add_album = $conn->query("INSERT INTO gallery_albums (album_name, album_prikazna) VALUES ('$album', '$album_prikazna')");
move_uploaded_file($_FILES['album_prikazna']['album_name'], $upload);
header("Location: fotogalerije.php?add_album_action=successfull");
}
?>
fotogalerije.php
<div class="container">
<!--Images-->
<div class="">
<h3>Arhivi</h3>
<form method="post" action="add-album.php">
<label>Dodaj novi album:</label><br>
<input type="text" name="album_name" /> <input type="submit" name="submit_album" value="Add" /><br>
<input type="file" class="mt-3" name="album_prikazna">
</form><br>
<?php
if (isset($_GET["add_album_action"])) {
if ($_GET["add_album_action"] == "successfull") { ?>
Nov album dodan!<br><br>
<?php }
}
?>
<div class="">
<?php
$albums = $conn->query("SELECT * FROM gallery_albums");
while ($album_data = $albums->fetch_assoc()) {
$photos = $conn->query("SELECT * FROM gallery_photos WHERE album_id = ".$album_data["album_id"]."");
?>
<div class="p-0 m-0">
<img src="<?php echo $album_data['album_prikazna']; ?>" width="125" class="p-1" />
<a href="view-album.php?album_id=<?php echo $album_data["album_id"] ?>">
<?php echo $album_data["album_name"];
$imagePrikazna = $album_data["album_prikazna"];
?>
(<?php echo $photos->num_rows; ?>)</a>
<?php }
?>
</div>
</div>
</div>
</div>
<!--!Images-->

How do I remain the image when I update edit form?

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();
}
?>

How to debug a HTML/PHP form not submitting properly

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 :-/

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'];

Updation not working using pdo in 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'];

Categories