Update row data with id not carrying id forward - php

Have being trying this query for 3 days now. I have a list of rows here: http://prntscr.com/dick00. All what I want to is to edit and delete each row respectively. For some reason the id is not carrying forward and no record is updating.
When I click on edit in access.php I get edit_access.php?id= in address bar.
Here is my link in access.php
<td><a href="edit_access.php?id=<?php echo $row['id']; ?>"><i class="fa fa-edit"></i>edit</td>
edit_access.php
EDIT 1: php code
<?php
// start session
session_start();
// error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['user_type'])){
header('Location: index.php');
}
// include connection
require_once('include/connection.php');
// set user session variables
$userId = $_SESSION['user_id'];
$error = [] ;
if(isset($_POST['update']))
{
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$therapist = $_POST['therapist'];
$access_type = $_POST['access_type'];
$code = $_POST['code'];
$created_at = $_POST['created_at'];
$postcode = $_POST['postcode'];
// validate form field
if (empty($firstname)){
$error[] = 'Field empty, please enter patient first name';
}
if (empty($lastname)){
$error[] = 'Field empty, please enter patient last name';
}
if (empty($therapist)){
$error[] = 'Field empty, please enter your name';
// $error = true;
}
if (empty($code)){
$error[] = 'Field empty, please enter patient access code';
// $error = true;
}
if (empty($access_type)){
$error[] = 'Field empty, please check access type';
// $error = true;
}
if (empty($postcode)){
$error[] = 'Field empty, please enter patient postcode';
// $error = true;
}
//if no errors have been created carry on
if(empty($error)){
$updated_at = date('Y-m-d');
// ************* UPDATE PROFILE INFORMATION ************************//
if(!($stmt = $con->prepare("UPDATE access SET firstname = ?, lastname = ?, therapist = ?, access_type = ?, postcode = ?, code = ?, updated_at = ?
WHERE id = ?"))) {
echo "Prepare failed: (" . $con->errno . ")" . $con->error;
}
if(!$stmt->bind_param('sssssssi', $firstname, $lastname, $therapist, $access_type, $postcode, $code, $updated_at, $userId)){
echo "Binding paramaters failed:(" . $stmt->errno . ")" . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: (" . $stmt->errno .")" . $stmt->error;
}
if($stmt) {
$_SESSION['main_notice'] = '<div class="alert alert-success">"Access Code Added successfully!"</div>';
header('Location: access.php');
exit;
}else{
$_SESSION['main_notice'] = '<div class="alert alert-danger">"Some error, try again"</div>';
header('Location: '.$_SERVER['PHP_SELF']);
}
}
}
// title page
$title = "Edit Access Record | Allocation | The Whittington Center";
// include header
require_once('include/header.php');
?>
<?php
if(isset($_GET['id'])){
$userId = $_GET['id'];
}
else{
$userId = $_POST['user_id'];
// mysqli_close($con);
$stmt = $con->prepare("SELECT * FROM access WHERE id = ?");
$stmt->bind_param('s', $userId);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0) {
echo 'No Data Found for this user';
}else {
$stmt->bind_result($firstname, $lastname, $therapist, $access_type, $postcode, $code);
while ($row = $stmt->fetch());
$stmt->close();
}
?>
EDIT 2: HTML part
<h2 class="text-light text-greensea">Edit Access Record</h2>
<form name="access" class="form-validation mt-20" novalidate="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" autocomplete='off'>
<div class="form-group">
<input type="text" name="firstname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' firstname ']; } ?>' placeholder='firstname'></td>
</div>
<div class="form-group">
<input type="text" name="lastname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' lastname ']; } ?>' placeholder='lastname'></td>
</div>
<div class="form-group">
<input type="text" name="therapist" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' therapist ']; } ?>' placeholder='therapist'></td>
</div>
<?php $access_type = $access_type; ?>
<div class="form-group ">
<label for="work status">Access Type</label>
<div name="access_type" value='<?php if(isset($error)){ echo $_POST[' access_type ']; } ?>'>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($work_status) && $access_type == "Keysafe") echo "checked"; ?> value="Keysafe"><i></i>Keysafe
</label>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($access_type) && $access_type == "keylog") echo "checked"; ?> value="keylog"><i></i>Keylog
</label>
</div>
</div>
<div class="form-group">
<input type="text" name="code" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' code ']; } ?>' placeholder='access code'></td>
</div>
<div class="form-group">
<input type="text" name="postcode" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' postcode ']; } ?>' placeholder='postcode'></td>
</div>
<div class="form-group text-left mt-20">
<button type="update" class="btn btn-primary pull-right" name="update" id='update'>Add Access</button>
<!-- <label class="checkbox checkbox-custom-alt checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label> -->
<a href="access.php">
<button type="button" class="btn btn-greensea b-0 br-2 mr-5">Back</button>
</a>
</div>
</form>
</div>
<!-- end of container -->
Thanks guy's for requesting for more code... i hope have given enough code sample.

you most put your id inside of a hidden input in your html form like this:
<input type="hidden" name="itemId" value="<?php echo '$_GET['id']'?>">
and then when you submit your form you have itemId in side $_POST['itemId'] variable.
EDIT:
I must describe scenario for you. maybe you got the point.
you have a list of access witch in every row has this tag:
access ....
in your access-form.php you have a form with this structure:
<form method="post" action="edit-access.php">
.....
<input type="hidden" name="id" value="<?php echo $_GET['id']?>">
.....
</form>
next in your edit-access.php you can access to this id by this syntax:
echo $_POST['id'];

Related

It tried updating to database but it is not working

<?php
include('config/db_connect.php');
$title = $email = $ingredients ='';
$errors = array('email'=>'', 'title'=>'', 'ingredient'=>'');
if(isset($_POST['update'])){
//Check email
if(empty($_POST['email'])){
$errors['email'] ='an email is required <br />';
} else{
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email'] = 'Email must be a valid email address';
}
}
//Check title
if(empty($_POST['title'])){
$errors['title'] ='a title is required <br />';
} else{
$title = $_POST['title'];
if(!preg_match('/^[a-zA-Z\s]+$/', $title)){
$errors['title'] = 'Title must be letters and spaces only';
}
}
//Check ingredients
if(empty($_POST['ingredients'])){
$errors['ingredient'] = 'at least one ingredent is required <br />';
} else{
$ingredients = $_POST['ingredients'];
if(!preg_match('/^([a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $ingredients)){
$errors['ingredient'] = 'ingredients must be a comma separated list';
}
}
if(array_filter($errors)){
//echo 'errors in the form';
}else{
$id_to_update = mysqli_real_escape_string($conn, $_POST['$id_to_update']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$title = mysqli_real_escape_string($conn, $_POST['title']);
$ingredients = mysqli_real_escape_string($conn, $_POST['ingredients']);
//create SQL
$sql = "UPDATE pizzas SET email='$email', title='$title', ingredients='$ingredients' WHERE id=$id_to_update";
echo $sql;
//save to db and check
if(mysqli_query($conn, $sql)){
//sucess
header('Location: index.php');
}else{
//errors
echo 'query error =' .mysqli_error($conn);
}
}
}
//check GET Request id param
if(isset($_GET['id'])){
$id = mysqli_real_escape_string($conn, $_GET['id']);
// make sql
$sql = "SELECT * FROM pizzas WHERE id = $id";
//get query result
$result = mysqli_query($conn, $sql);
//fetch result in array format
$pizza = mysqli_fetch_assoc($result);
mysqli_free_result($result);
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<section class="container grey-text">
<h4 class="center">Edit Pizza</h4>
<form class="white" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<label >Your Email:</label>
<input type="text" name="email" value="<?php echo htmlspecialchars($pizza['email']); ?>">
<div class="red-text"><?php echo $errors['email']; ?></div>
<label >Pizza Title:</label>
<input type="text" name="title" value="<?php echo htmlspecialchars($pizza['title']); ?>">
<div class="red-text"><?php echo $errors['title']; ?></div>
<label >ingredients(comma separated):</label>
<input type="text" name="ingredients" value="<?php echo htmlspecialchars($pizza['ingredients']); ?>">
<div class="red-text"><?php echo $errors['ingredient']; ?></div>
<div class="center">
<input type="submit" name="update" value="Update Pizza" class="btn brand z-depth-0">
Back
</div>
</form>
</section>
<?php include('templates/footer.php');?>
</html>
Undefined index: $id_to_update in C:\xampp\htdocs\pizza\edit.php on line 36
UPDATE pizzas SET email='ajisafejerry#gmail.com', title='fish Supreme', ingredients='fish, tomatoes, cheese, pepper' WHERE id=query error =You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
You missed to post the "id" in your form you should add it.
<input type="hidden" name="id_to_update" value="<?php echo $id ?>">
And you have a typo, remove the dollar sign, it is a name not a variable.
$id_to_update = mysqli_real_escape_string($conn, $_POST['id_to_update']);
// ^ here
And if you want, depending on your specifications, you can tweak your redirect after the update to smth. like this.
header('Location: sql.php?id='.$id_to_update);

values added as blank spaces php sql

<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $fullname = $password = $age = $phonenumber = $role = $email = "";
$username_err = $fullname_err = $password_err = $age_err = $phonenumber_err =
$role_err = $email_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
if(var_dump($_POST["username"]))
{
$input_name = trim($_POST["username"]);
if(empty($input_name)){
$username_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$username_err = "Please enter a valid name.";
} else{
$username = $input_name;
}
}
// Validate fullname
if(var_dump($_POST["username"]))
{
$input_fname = trim($_POST["fullname"]);
if(empty($input_fname)){
$fullname_err = "Please enter a name.";
} elseif(!filter_var($input_fname, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$fullname_err = "Please enter a valid name.";
} else{
$fullname = $input_fname;
}
}
// Validate age
if(var_dump($_POST["age"]))
{
$input_age = trim($_POST["age"]);
if(empty($input_age)){
$age_err = "Please enter your age.";
} else{
$age = $input_age;
}
}
// Validate phonenumber
if(var_dump($_POST["phonenumber"]))
{
$input_phonenumber = trim($_POST["phonenumber"]);
if(empty($input_phonenumber)){
$phonenumber_err = "Please enter a proper phonenumber.";
} else{
$phonenumber = $input_phonenumber;
}
}
// Validate role
if(var_dump($_POST["role"]))
{
$input_role = trim($_POST["role"]);
if(empty($input_role)){
$role_err = "Please enter a proper role.";
} else{
$role = $input_role;
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($fullname_err) && empty($age_err) &&
empty($phonenumber_err) && empty($role_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (user_name, full_name, age, phone_number,
role) VALUES (?, ?, ?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssiis", $param_username,
$param_fullname, $param_age, $param_phonenumber, $param_role);
// Set parameters
$param_username = $username;
$param_fullname = $fullname;
$param_age = $age;
$param_phonenumber = $phonenumber;
$param_roll = $roll;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "Records created successfully. Redirect to landing page";
// Records created successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>ADD NEW USERS</h2>
</div>
<p>Please fill this form to start trading.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err;?></span>
</div>
<div class="form-group <?php echo (!empty($fullname_err)) ? 'has-error' : ''; ?>">
<label>FULL NAME</label>
<input type="text" name="fullname" class="form-control" value="<?php echo $fullname; ?>">
<span class="help-block"><?php echo $fullname_err;?></span>
</div>
<div class="form-group <?php echo (!empty($age_err)) ? 'has-error' : ''; ?>">
<label>AGE</label>
<input type="number" name="age" class="form-control" value="<?php echo $age; ?>">
<span class="help-block"><?php echo $age_err;?></span>
</div>
<div class="form-group <?php echo (!empty($phonenumber_err)) ? 'has-error' : ''; ?>">
<label>PHONENUMBER</label>
<input type="number" name="phonenumber" class="form-control" value="<?php echo $phonenumber; ?>">
<span class="help-block"><?php echo $phonenumber_err;?></span>
</div>
<div class="form-group <?php echo (!empty($role_err)) ? 'has-error' : ''; ?>">
<label>ROLE </label>
<form action="" method="post">
<input type="radio" name="radio" value="<php echo $role; ?>">INVESTOR
<input type="radio" name="radio" value="<php echo $role; ?>">MANAGER
<span class="help-block"><?php echo $role_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
THERE ARE NO ERRORS HOWEVER A BLANK ROW GETS ADDED EVERY TIME I SUBMIT
table in the database is as follows
user_id
user_name
user_password
full_name
age
phone_number
email
role
I am using php 7.2 and sql from phpmyadmin server is running on xampp
Tried using only Trim without isset that gave an undefined index error for all parameters
Your main issue:
In your form every input has the name="name".
It should be "username", "fullname", "phonenumber",..
This is why you receive no values in $_POST['username'].
So why don't you get any error? Because you don't set one if isset($_POST['username']) is false:
if(isset($_POST["username"]))
{
$input_name = trim($_POST["username"]);
if(empty($input_name)){
$username_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$username_err = "Please enter a valid name.";
} else{
$username = $input_name;
}
}
// NO ELSE here. here you should set $fullname_err
Consequently on INSERT you bind to the original initialized value of $username, which is "".

PDO error 42000

i had an error when i run my code and i don't understand this error
error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE UserID = 'ahmed' SET Username = 'adasda#dmail.ck',Email = 'ahmed',FullName' at line 1 in C:\wamp64\www\eC
<?php
/*
==============================================================
= Manage Member do
= you can Add | Edit | Delete Members from here
==============================================================
*/
session_start();
$pageTitle = 'Members';
if(isset($_SESSION['Username'])){
include 'init.php';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage';
// $do= '';
//
// if(isset($_GET['do'])){
//
// $do = $_GET['do'];
// }else {
// $do = 'Manage';
// }
// start Manage do
if ($do == 'Manage') {
echo 'welcom in manage do';
//Manage page
}elseif ($do == 'Edit') { //edit page
// check If the GET Request is Numeric && Get the Integer value of it
$userid = isset($_GET['userid']) && ($_GET['userid']) ? intval($_GET['userid']) : 0;
// Select the row of user from the table
// select All data Depend on this Id
$stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1");
// extract Query
$stmt->execute(array($userid));
// Fetch the data
$row = $stmt->fetch();
// the row count
$count = $stmt->rowCount(); // to count the row in the table
if ($stmt->rowCount() > 0) {
?>
<h1 class="text-center">Edit Member</h1>
<div class="container">
<form class="form-horizontal" action="?do=Update" method="POST">
<input type="hidden" name='userid' value="<?php echo $userid ?>"/>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Username</label>
<div class="col-sm-10">
<input type="text" name="username" class="form-control" value="<?php echo $row['Username'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Password</label>
<div class="col-sm-10">
<input type="hidden" name="oldpassword"/>
<input type="password" name="newpassword" class="form-control" autocomplete="new-password"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">E-mail</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" value="<?php echo$row['Email'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Full-Name</label>
<div class="col-sm-10">
<input type="text" name="full" class="form-control" value="<?php echo$row['FullName'] ?>" autocomplete="off" />
</div>
</div>
<div class="form-group form-group-lg">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="save" class="btn btn-primary btn-lg" />
</div>
</div>
</form>
</div>
<?php
}else {
echo "you are not welcom in this page ";
}
}
// update page
elseif ($do == 'Update') {
echo "<h1 class='text-center'> welcom in the update page </h1>";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
# get the variable from the form
$id = $_POST['userid'];
$user = $_POST['username'];
$email= $_POST['email'];
$name = $_POST['full'];
//echo $id . $user . $pass . $name;
$stmt = $con->prepare('UPDATE users WHERE UserID = ? SET Username = ?,Email = ?,FullName = ?,');
$stmt->execute(array($user,$email,$name,$id));
echo $stmt->rowCount() . "Record Updated";
}else {
echo "you cant brows this page directly";
}
}
include $tpl . 'footer.php';
}else {
header('location: index.php');
exit();
}
?>
ommers\first_project\admin\members.php on line 110
Your update query is incorrect, you need to use the following:
$stmt = $con->prepare('UPDATE users SET Username = ?,Email = ?,FullName = ? Where UserId =?');
And change the rest of the code accordingly.

Can get data on editing part <br /><b>Notice</b>: Undefined variable: row in

I am new in PHP. I keep on getting "undefined variable row in". I already read and try suggestion from other related question and answer here but nothing works for me.
PHP code
<?php
session_start();
require_once('dbConfig.php');
if(isset($_GET['ass_id'])){
$ass_id = $_GET['ass_id'];
$sql = "select * from beedass where ass_id=".$ass_id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
}else{
$errorMsg = 'Could not select a record';
}
}
if(isset($_POST['btnUpdate'])){
$subject = $_POST['subject'];
$date = $_POST['date'];
$content = $_POST['content'];
if(empty($subject)){
$errorMsg = 'Please input subject course';
}elseif(empty($date)){
$errorMsg = 'Please input date to be passed';
}elseif(empty($content)){
$errorMsg = 'Please input assignment content';
}
//check upload file not error than insert data to database
if(!isset($errorMsg)){
$sql = "update beedass
set subject = '".$subejct."',
date = '".$date."',
content = '".$content."'
where ass_id=".$ass_id;
$result = mysqli_query($conn, $sql);
if($result){
$successMsg = 'New record updated successfully';
header('refresh:5;view_beedass.php');
}else{
$errorMsg = 'Error '.mysqli_error($conn);
}
}
}
?>
Keep on getting error on this line on my HTML code:
<form action="edit_beedass.php?ass_id=<?php echo $row['ass_id'];?>"
method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label for="name" class="col-md-2">Subject Course</label>
<div class="col-md-10">
<input type="text" name="subject" class="form-control" value="<?
php echo $row['subject'] ; ?>">
</div>
</div>
<div class="form-group">
<label for="position" class="col-md-2">Date and Time to be
Passed</label>
<div class="col-md-10">
<input type="text" name="date" class="form-control" value="<?php
echo (isset($row['date']))? $row['date'] : $date ; ?>">
</div>
</div>
<div class="form-group">
<label for="position" class="col-md-2">Assignment Content</label>
<div class="col-md-10">
<input type="text" name="content" class="form-control" value="<?
php echo (isset($row['content'])) ; ?>">
</div>
</div>
The error I get is undefined variable row in echo $row['subject'], echo $row['date'] and echo $row['content'].

Data ain't changed after submitted to mysql

i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.

Categories