PHP MySQL not updating for CRUD app - php

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

Related

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

Unable to connect the Database and Handle the POST request

Hello I am working with a predefined template and I am trying to fetch some data from the input space in form of POST/GET request using php. But I am unable to do so, How can I integrate the database and handle the php parameters?
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
?>
}
Hello change your code to this
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</div>
For the database connection it depends on which database you are working with but you can start here. A simple Google query with provide you what you are looking for
I put together an example for you that may come in handy. This shows how you can use PHP to submit a form print some values that the user enters on the page. I also included some commented out code that you can copy and move to a seperate script and call by changing the action value to the file path.
The PHP script:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
$data = [
"BOB" => "AWESOME",
"JOE" => "AVERAGE",
"TOM" => "COOL"
];
}
?>
Next, we have the form. I added this form because you need it to submit to the page. (Well you don't "need" it but it makes life easy.)
<div class="container">
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Adhaar"
name="adhaar"
required
value="<?= isset($_POST['adhaar']) ? $_POST['adhaar'] : '' ?>">
</div>
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Town/City"
name="city"
required
value="<?= isset($_POST['city']) ? $_POST['city'] : '' ?>">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">CLICK ME!</button>
</div>
</form>
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
</div>
Last piece of the file simply outputs information onto the page if it finds it in the $_POST global array.
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
This commented out part here you can use to pull data from the database and pass it back to your page. If you are just starting it's cool to tinker but ideally you DO NOT want to make calls to the db on the same page as your view. It should live in it's own file.
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
You should Try This Code ..This is working i Simply add a submit button to it
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<form method="GET" action="xxx.php">
<input type="text" placeholder="Adhaar" name="Adhaar" required="" />
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="" />
<input type="submit" name="submit" value="show">
<?php
if(isset($_GET['submit']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</form>
</div>

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>

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