I am retrieving values from the database into the form for update, on the press of the submit button, the values should get updated.
Here's the code:
PostUpdate.php:
<?php
session_start();
$username=$_SESSION['uname'];
$cn=mysqli_connect("localhost", "root", "", "testdb");
// Define variables and initialize with empty values
$course = $category = "";
$title = $descp = "";
// Processing form data when form is submitted
if(isset($_POST["pid"]) && !empty($_POST["pid"])){
// Get hidden input value
$pid = $_POST["pid"];
// Check input errors before inserting in database
if(empty($course) && empty($category) && empty($title) && empty($descp)){
// Prepare an update statement
$sql = "UPDATE posts SET course=?, category=?, title=?, descp=? WHERE pid=?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssssi", $param_course, $param_category, $param_title, $param_descp, $param_pid);
// Set parameters
$param_course = $course;
$param_category = $category;
$param_title = $title;
$param_descp = $descp;
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: CAposts.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($cn);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["pid"]) && !empty(trim($_GET["pid"]))){
// Get URL parameter
$pid = trim($_GET["pid"]);
// Prepare a select statement
$sql = "SELECT * FROM posts WHERE pid = ?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_pid);
// Set parameters
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$pid = $row['pid'];
$uname = $row['uname'];
$course = $row['course'];
$category = $row['category'];
$pdate = $row['pdate'];
$title = $row['title'];
$descp = $row['descp'];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: CAposts.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($cn);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: CAposts.php");
exit();
}
}
?>
<html>
<head>
<title>IMEDTalks-Post-
<?php echo $title;?>
</title>
<link href="./css/bootstrap.min.css" rel="stylesheet" />
<script src="./scripts/jquery-3.3.1.min.js"></script>
<script src="./scripts/bootstrap.min.js"></script>
<style>
/* Make the image fully responsive */
.carousel-inner img {
width: 100%;
height: 30%;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2 class="text-center">Update Post</h2>
</div>
<p class="text-center">Please edit the input values and submit to update the post.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<div class="row">
<label class="col-form-label col-md-1 offset-3" for="course">Course:</label>
<div class="col-md-2">
<select name="course" class="form-control" required>
<option value="<?php echo $course;?>" selected>
<?php echo $course;?>
</option>
<option value="">Choose any:</option>
<option value="comp">Comp</option>
<option value="theo">Theory</option>
</select>
</div>
<label class="col-form-label col-md-1" for="category">Category:</label>
<div class="col-md-3">
<select name="category" class="form-control" required>
<option value="<?php echo $category;?>" selected>
<?php echo $category;?>
</option>
<option value="">Choose any:</option>
<option value="plang">Programming Language</option>
<option value="web">Web Technologies</option>
<option value="maths">Mathematics and Statistics</option>
<option value="others">Others</option>
</select>
</div>
</div>
</div>
<div class="form-group row">
<label for="title" class="col-form-label col-md-2">Title:
</label>
<div class="col-md-10">
<input type="text" class="form-control" value="<?php echo $title;?>" name="title" required>
</div>
</div>
<div class="form-group row">
<label for="desc" class="col-form-label col-md-12">Description:
</label>
<div class="col-md-12">
<textarea class="form-control" name="descp" rows="20" required><?php echo $descp;?></textarea>
</div>
</div>
<input type="hidden" name="pid" value="<?php echo $pid;?>" />
<div class="form-group row">
<div class="col-md-4 offset-4">
<a href="CAposts.php"><button type="button" name="cancel"
class="btn-lg btn-danger">Cancel</button></a>
</div>
<div class="col-md-4">
<button type="submit" name="update" class="btn-lg btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Here, i am using pid which is being bought from the previous page where the data is listed in table format, and on the click of a button there, that data/post gets loaded into the form for editing and updating the same using the pid(primary key in my database table)
Iam using bootstrap 4.
Problem i am facing:
The update operation is performed without any errors using the pid, but the values of course, category, title, description gets set to blank in database table after this update operation.
I can't figure out whats going wrong here.
Related
I am retrieving values from the database into the form for update, on the press of submit button.
The values do get retrieved but update process fails without any error.
Here's the code:
<?php
session_start();
$username=$_SESSION['uname'];
$cn=mysqli_connect("localhost", "root", "", "testdb");
// Define variables and initialize with empty values
$course = $category = "";
$title = $descp = "";
// Processing form data when form is submitted
if(isset($_POST["pid"]) && !empty($_POST["pid"])){
// Get hidden input value
$pid = $_POST["pid"];
// Check input errors before inserting in database
if(empty($course) && empty($category) && empty($title) && empty($descp)){
// Prepare an update statement
$sql = "UPDATE posts SET course=?, category=?, title=?, descp=? WHERE pid=?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssssi", $param_course, $param_category, $param_title, $param_descp, $param_pid);
// Set parameters
$param_course = $course;
$param_category = $category;
$param_title = $title;
$param_descp = $descp;
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: CAposts.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($cn);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["pid"]) && !empty(trim($_GET["pid"]))){
// Get URL parameter
$pid = trim($_GET["pid"]);
// Prepare a select statement
$sql = "SELECT * FROM posts WHERE pid = ?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_pid);
// Set parameters
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$pid = $row['pid'];
$uname = $row['uname'];
$course = $row['course'];
$category = $row['category'];
$pdate = $row['pdate'];
$title = $row['title'];
$descp = $row['descp'];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: CAposts.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($cn);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: CAposts.php");
exit();
}
}
?>
<html>
<head>
<title>IMEDTalks-Post-
<?php echo $title;?>
</title>
<link href="./css/bootstrap.min.css" rel="stylesheet" />
<script src="./scripts/jquery-3.3.1.min.js"></script>
<script src="./scripts/bootstrap.min.js"></script>
<style>
/* Make the image fully responsive */
.carousel-inner img {
width: 100%;
height: 30%;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2 class="text-center">Update Post</h2>
</div>
<p class="text-center">Please edit the input values and submit to update the post.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<div class="row">
<label class="col-form-label col-md-1 offset-3" for="course">Course:</label>
<div class="col-md-2">
<select name="course" class="form-control" required>
<option value="<?php echo $course;?>" selected>
<?php echo $course;?>
</option>
<option value="">Choose any:</option>
<option value="comp">Comp</option>
<option value="theo">Theory</option>
</select>
</div>
<label class="col-form-label col-md-1" for="category">Category:</label>
<div class="col-md-3">
<select name="category" class="form-control" required>
<option value="<?php echo $category;?>" selected>
<?php echo $category;?>
</option>
<option value="">Choose any:</option>
<option value="plang">Programming Language</option>
<option value="web">Web Technologies</option>
<option value="maths">Mathematics and Statistics</option>
<option value="others">Others</option>
</select>
</div>
</div>
</div>
<div class="form-group row">
<label for="title" class="col-form-label col-md-2">Title:
</label>
<div class="col-md-10">
<input type="text" class="form-control" value="<?php echo $title;?>" name="title" required>
</div>
</div>
<div class="form-group row">
<label for="desc" class="col-form-label col-md-12">Description:
</label>
<div class="col-md-12">
<textarea class="form-control" name="descp" rows="20" required><?php echo $descp;?></textarea>
</div>
</div>
<input type="hidden" name="pid" value="<?php echo $pid;?>" />
<div class="form-group row">
<div class="col-md-4 offset-4">
<a href="CAposts.php"><button type="button" name="cancel"
class="btn-lg btn-danger">Cancel</button></a>
</div>
<div class="col-md-4">
<button type="submit" name="update" class="btn-lg btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
PS:
pid is being bought from the previous page where the data is listed in table format, and on the click of the button, that data/post gets loaded into the form for editing using the pid, which is primary key in my database table.
using bootstrap 4.
Edited after first comments.
You have 5 columns in your query but you only bind 4 of them, so you forgot an s
$sql = "UPDATE posts SET course=?, category=?, title=? descp=? WHERE pid=?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sssi", $param_course, $param_category, $param_title, $param_descp, $param_pid);
Here a cleaner code for your update:
$stmt = $conn->prepare("UPDATE posts SET course=?, category=?, title=?, descp=? WHERE pid=?");
$stmt->bind_param("ssssi", $course, $category, $title, $descp, $pid);
$stmt->execute();
I just saw that you are trying to display all your data from DB using
// Prepare a select statement
$sql = "SELECT * FROM posts WHERE pid = ?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_pid);
// Set parameters
$param_pid = $pid;
And also, the value of all your form is using these informations fetched from DB, which is nothing since, i just can't understand. You are trying to fetching all your data using a variable which comming from data of DB itself...
Try something, change the hidden form for your ID and use this (if you have data in db using id 1)
<input type="hidden" name="pid" value="1" />
Validate function
function validate(add_app_form){
var valid = true;
var userTxt = document.getElementById("patient_name").value;
var dateTxt = document.getElementById("app_date").value;
var timeTxt = document.getElementById("app_time").value;
var oldName = document.getElementById("select_old").value;
if(userTxt == "" && dateTxt == "" && timeTxt == "" && oldName == "choose")
{
//$("#lblTxt").text("Username and Password are required!");
$('#patient_name').css('border-color', 'red');
$('#app_date').css('border-color', 'red');
$('#app_time').css('border-color', 'red');
$('#select_old').css('border-color', 'red');
$("#add_app_lbl").text("Please Fill all the form");
valid = false;
}
if(userTxt == "" && oldName == "choose")
{
$('#patient_name').css('border-color', 'red');
$("#add_app_lbl").text("Please Add Patient Name Or select an old patient");
valid = false;
}
if(dateTxt == "")
{
$('#app_date').css('border-color', 'red');
$("#add_app_lbl").text("Please Add a Date");
valid = false;
}
return valid;
}
EDITED CODE
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
EDITED CODE 2
<form class="form-horizontal" id="add_app_form" method="post" action="add_appoint.php" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" id="add_app_btn" name="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
I have a php code that take values from a form and add them into MySQL database.
First part of the PHP code, see if the admin choose an already exist patient from drop list, then add a date and time of an appointment with a reason.
Then values are posted into PHP code where we see if we have already an appointment in those date and time. If not ($appExistStmtCount == 0) then go and insert an appointment.
The problem is that nothing added to database and can't see any PHP errors echoed.
Here is the PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
And here the HTML form:
<form class="form-horizontal" id="add_app_form" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submi;" id="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
PS
Values can be seen in the URL but the page just refresh and nothing added
Your form has no method, so it's passing data through get. You need to add method="post" to your form.
Edit. As #u_mulder mentioned, you need to add name attribute to your button for the check in your php if the button is clicked.
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'];
It's a simple code but i can't understand where is my mistake. I want to display succesfull message under the form when i click the submit but the message stays there all the time. When i enter in the page where the form is the message is under the form. How to take it out only when the query is succesfull ?
<?php
$posted = false;
if(isset($_POST['add']))
{
$posted = true;
$email = $_POST['email'];
$name = $_POST['name'];
$rate = $_POST['rate'];
$comment = $_POST['comment'];
$dth = date("Y-m-d H:i:s");
$q = "INSERT INTO reviews(email, name, rate, comment, date_created) VALUES ('$email', '$name', '$rate', '$comment', '$dth')";
$k = mysqli_query($con,$q);
}
?>
<body>
<h1>Leave a review</h1>
<div class="error-conteiner">
</div>
<div class="clear"></div>
<form action="" method="post" class="form-content">
<div class="left">
<div class="field">
<label>E-mail <span class="required">*</span></label>
<input type="text" value="" name="email" class="required-field" data-validate="email"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Name</label>
<input type="text" value="" name="name"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Rate</label>
<select name="rate">
<option value=''>Choose rate</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
</div>
<div class="left">
<label>Comment <span class="required">*</span></label>
<textarea name="comment" class="comment required-field"></textarea>
</div>
<input type="submit" value="Send" class="btn" name="add" />
</form>
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
</body>
</html>
Maybe it is not professional and nice solution, but works well, if you make a query after the post with ex. $email and $name or other parameters. If the result is not empty, then you can put the results or just a simple message also into the output.
Replace
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with
<?php
if($posted===true){
if($k) echo "Thank you for your comment!";
else die(mysqli_error());
}
?>
Maybe you have to put {} after your first if
Directly below:
$k = mysqli_query($con,$q);
add:
if(!$k) {
die(mysqli_error());
}
If the query wasn't executed, for whatever reason, show the error and stop.
You might consider adding a development mode variable or constant, because the mysqli_error() message is only valuable for the developer and the content is not for your users eyes. Anyway:
Replace:
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with:
if($posted === true) {
echo 'Thank you for your comment!';
}
The mysql error is handled, where it occurs.
The success message is only displayed, when successfully send.
It's also possible to make a header redirection on success. But that depends, on what you like.
if($posted === true) {
header('Location: success-message-page.php');
exit;
}