This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
ERROR :
Notice: Undefined index: cawangan_ppk in
C:\xampp\htdocs\eselenggaraMada\USER\laporanrosakU.php on line 62
Define Variables :
$tarikhisi = $nama = $namapelapor = $bahagian = $cawangan_ppk = $kategorirosak = $jenisrosak = $nosiri = $ringkasanrosak = "";
$tarikhisi_err = $nama_err = $namapelapor_err = $bahagian_err = $cawangan_ppk_err = $kategorirosak_err = $jenisrosak_err = $nosiri_err = $ringkasanrosak_err = "";
Line 62 :
$input_cawangan_ppk = trim($_POST["cawangan_ppk"]);
if(empty($input_cawangan_ppk)){
$cawangan_ppk_err = "Please enter an Cawangan.";
} else{
$cawangan_ppk = $input_cawangan_ppk;
}
CODE :
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: loginU.php");
exit;
}
?>
<?php
// Include config file
require_once "configU.php";
// Define variables and initialize with empty values
$tarikhisi = $nama = $namapelapor = $bahagian = $cawangan_ppk = $kategorirosak = $jenisrosak = $nosiri = $ringkasanrosak = "";
$tarikhisi_err = $nama_err = $namapelapor_err = $bahagian_err = $cawangan_ppk_err = $kategorirosak_err = $jenisrosak_err = $nosiri_err = $ringkasanrosak_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] = "POST"){
// Validate tarikh
$input_tarikhisi = trim($_POST["tarikhisi"]);
if(empty($input_tarikhisi)){
$tarikhisi_err = "Masukkan Tarikh.";
} else{
$tarikhisi = $input_tarikhisi;
}
// Validate nama
$input_nama = trim($_POST["nama"]);
if(empty($input_nama)){
$nama_err = "Masukkan Nama.";
} else{
$nama = $input_nama;
}
// Validate nama pelapor
$input_namapelapor = trim($_POST["namapelapor"]);
if(empty($input_namapelapor)){
$namapelapor_err = "Please enter a name.";
} elseif(!filter_var($input_namapelapor, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$namapelapor_err = "Please enter a valid name.";
} else{
$namapelapor = $input_namapelapor;
}
// Validate bahagian
$input_bahagian = trim($_POST["bahagian"]);
if(empty($input_bahagian)){
$bahagian_err = "Please enter an Bahagian.";
} else{
$bahagian = $input_bahagian;
}
// Validate cawangan
$input_cawangan_ppk = trim($_POST["cawangan_ppk"]);
if(empty($input_cawangan_ppk)){
$cawangan_ppk_err = "Please enter an Cawangan.";
} else{
$cawangan_ppk = $input_cawangan_ppk;
}
// Validate kategorirosak
$input_kategorirosak = trim($_POST["kategorirosak"]);
if(empty($input_kategorirosak)){
$kategorirosak_err = "Please enter an kategorirosak.";
} else{
$kategorirosak = $input_kategorirosak;
}
// Validate Jenis Kerosakkan
$input_jenisrosak = trim($_POST["jenisrosak"]);
if(empty($input_jenisrosak)){
$jenisrosak_err = "Please enter an Jenis Kerosakkan.";
} else{
$jenisrosak = $input_jenisrosak;
}
// Validate No.Siri
$input_nosiri = trim($_POST["nosiri"]);
if(empty($input_nosiri)){
$nosiri_err = "Please enter an No Siri.";
} else{
$nosiri = $input_nosiri;
}
// Validate Ringkasan Kerosakkan
$input_ringkasanrosak = trim($_POST["ringkasanrosak"]);
if(empty($input_ringkasanrosak)){
$ringkasanrosak_err = "Please enter an Ringkasan Kerosakkan.";
} else{
$ringkasanrosak = $input_ringkasanrosak;
}
// Check input errors before inserting in database
if(empty($tarikhisi_err) && empty($nama_err) && empty($namapelapor_err) && empty($bahagian_err) && empty($cawangan_ppk_err) && empty($kategorirosak_err) && empty($jenisrosak_err)
&& empty($nosiri_err) && empty($ringkasanrosak_err)){
// Prepare an insert statement
$sql = "INSERT INTO laporankerosakkan (tarikhisi , nama , namapelapor , bahagian , cawangan_ppk , kategorirosak , jenisrosak , nosiri , ringkasanrosak) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sssssssss", $param_tarikhisi, $param_nama, $param_namapelapor , $param_bahagian, $param_cawangan_ppk, $param_kategorirosak, $param_jenisrosak,
$param_nosiri, $param_ringkasanrosak);
// Set parameters
$param_tarikhisi = $tarikhisi;
$param_nama = $nama;
$param_namapelapor = $namapelapor;
$param_bahagian = $bahagian;
$param_cawangan_ppk = $cawangan_ppk;
$param_kategorirosak = $kategorirosak;
$param_jenisrosak = $jenisrosak;
$param_nosiri = $nosiri;
$param_ringkasanrosak = $ringkasanrosak;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header ("location: homeU.php");
exit();
} else{
echo "Something went wrong. Please try again later...";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
var_dump($_POST);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<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>
<link rel="icon" type="image/jpg" href="..\image/logo1.png">
<link rel="stylesheet" type="text/css" href="..\style/style.css">
<link rel="stylesheet" type="text/css" href="style/image_gallery.css">
<link rel="stylesheet" href="..\style\3css.css">
<link rel="stylesheet" href="style\about.css">
<link rel="stylesheet" href="..\style\top.css">
<link rel="stylesheet" type="text/css" href="..\style/form.css">
<meta charset="UTF-8">
<title>ADUAN KEROSAKKAN</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
</style>
</head>
<?php
// Include config file
require_once "configU.php";
?>
<body>
<center>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to e-selenggaraMada.</h1>
</div>
<tr>
<div>
</div>
</div>
<ul>
<li>UTAMA</li>
<li><a class="active" href="laporanrosakU.php">ADUAN KEROSAKKAN</a></li>
<li>SENARAI LAPORAN</li>
<li>HUBUNGI</li>
<li>CARI</li>
</ul>
<iframe src="http://free.timeanddate.com/clock/i628bi4j/n3832/tlmy40/fn7/fs20/fc33f/tct/pct/tt0/th2" frameborder="0" width="389" height="30" allowTransparency="true" align="right"></iframe>
</p>
<!--Form section-->
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Borang Aduan Kerosakkan</h2>
</div>
<p><h3>Masukkan Maklumat.</h3></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($tarikhisi_err)) ? 'has-error' : ''; ?>">
<label>Tarikh</label>
<input type="text" name="tarikhisi" class="form-control" value="<?php echo $tarikhisi; ?>">
<span class="help-block"><?php echo $tarikhisi_err;?></span>
</div>
<div class="form-group <?php echo (!empty($nama_err)) ? 'has-error' : ''; ?>">
<label>Nama</label>
<input type="text" name="nama" class="form-control" readonly value="<?php echo htmlspecialchars($_SESSION["username"]); ?>">
<span class="help-block"><?php echo $nama_err;?></span>
</div>
<div class="form-group <?php echo (!empty($namapelapor_err)) ? 'has-error' : ''; ?>">
<label>Nama Pelapor</label>
<input type="text" name="namapelapor" class="form-control" value="<?php echo $namapelapor; ?>">
<span class="help-block"><?php echo $namapelapor_err;?></span>
</div>
<div class="form-group <?php echo (!empty($bahagian_err)) ? 'has-error' : ''; ?>">
<label>Bahagian</label>
<select class="form-control" type="text" name="bahagian" id="bahagian" maxlength="12" placeholder="bahagian" required />
<option value="">-Sila Pilih-</option>
<?php
$result = mysqli_query($con, "SELECT * FROM bahagian ");
while (($data = mysqli_fetch_array($result)) != false)
echo '<option value="', $data['nama'],'">', $data['nama'],'</option>'
?>
</select>
</div>
<div class="form-group <?php echo (!empty($cawangan_ppk_err)) ? 'has-error' : ''; ?>">
<label>Cawangan/PPK</label>
<select class="form-control" type="text" name="cawangan" id="cawangan" maxlength="12" placeholder="bahagian" required />
<option value="">-Sila Pilih-</option>
<?php
$result = mysqli_query($con, "SELECT * FROM cawangan_ppk ");
while (($data = mysqli_fetch_array($result)) != false)
echo '<option value="', $data['nama'],'">', $data['nama'],'</option>'
?>
</select>
<span class="help-block"><?php echo $cawangan_ppk_err;?></span>
</div>
<div class="form-group <?php echo (!empty($kategorirosak_err)) ? 'has-error' : ''; ?>">
<label>kategorirosak</label>
<select class="form-control" type="text" name="kategorirosak" id="kategorirosak" maxlength="12" placeholder="kategorirosak" required />
<option value="">-Sila Pilih-</option>
<?php
$result = mysqli_query($con, "SELECT * FROM kategorirosak ");
while (($data = mysqli_fetch_array($result)) != false)
echo '<option value="', $data['nama'],'">', $data['nama'],'</option>'
?>
</select>
<span class="help-block"><?php echo $kategorirosak_err;?></span>
</div>
<div class="form-group <?php echo (!empty($jenisrosak_err)) ? 'has-error' : ''; ?>">
<label>Jenis Kerosakkan</label>
<select class="form-control" type="text" name="jenisrosak" id="jenisrosak" maxlength="12" placeholder="jenisrosak" required />
<option value="">-Sila Pilih-</option>
<?php
$result = mysqli_query($con, "SELECT * FROM jenisrosak ");
while (($data = mysqli_fetch_array($result)) != false)
echo '<option value="', $data['nama'],'">', $data['nama'],'</option>'
?>
</select>
<span class="help-block"><?php echo $jenisrosak_err;?></span>
</div>
<div class="form-group <?php echo (!empty($nosiri_err)) ? 'has-error' : ''; ?>">
<label>No.Siri Peralatan</label>
<input type="text" name="nosiri" class="form-control" value="<?php echo $nosiri; ?>">
<span class="help-block"><?php echo $nosiri_err;?></span>
</div>
<div class="form-group <?php echo (!empty($ringkasanrosak_err)) ? 'has-error' : ''; ?>">
<label>Ringkasan Kerosakkan</label>
<input type="text" name="ringkasanrosak" class="form-control" value="<?php echo $ringkasanrosak; ?>">
<span class="help-block"><?php echo $ringkasanrosak_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Batal Aduan
</form>
</div>
</div>
</div>
</div>
<center>
TUKAR KATA LALUAN
LOG KELUAR
</body>
</html>
any help are really appreciate, Thank You So Much
It says that the array you passed to the serve does not contain cawangan_ppk key, that is why it returned Undefined index. please provide a cawangan_ppk name in your form.
I think on this select tag you had missed it.
// change this
<select class="form-control" type="text" name="cawangan" id="cawangan" maxlength="12" placeholder="bahagian" required /></select>
// to this
<select class="form-control" type="text" name="cawangan_ppk" id="cawangan" maxlength="12" placeholder="bahagian" required /></select>
You can then do this declaration to be sure you have to return an error even cawangan_ppk exists or not.
$input_cawangan_ppk = $_POST["cawangan_ppk"] ? trim($_POST["cawangan_ppk"]) : '';
Related
I will describe my problems briefly. There are 2 main issues in my web app:
Date of Birth does not show in the edit page (DONE)
I cannot submit my record to the database (partly due to problem 1)
Here is my code:
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "students";
$mysqli = new mysqli($host, $username, $password, $database);
if (!$mysqli) {
die("Cannot connect to mysql");
}
if (isset($_POST['save'])) {
// Display errors if all fields are blank
$errors = [];
if (strlen(trim($_POST['student_id'])) === 0) {
$errors['student_id'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['first_name'])) === 0) {
$errors['first_name'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['last_name'])) === 0) {
$errors['last_name'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['email'])) === 0) {
$errors['email'] = "Không được để trống trường này";
} else {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email phải đúng định dạng';
}
}
if (strlen(trim($_POST['dob'])) === 0) {
$errors['dob'] = "Không được để trống trường này";
}
}
// If there is not any black field, show the information at the index page
$id = $_GET['id'];
$sql = "SELECT * FROM students WHERE id = $id";
$result = $mysqli->query($sql);
$students = $result->fetch_assoc();
print_r($students) ;
if (isset($errors) && count($errors) == 0) {
$student_id = $_POST['student_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$sql = "UPDATE students(student_id, first_name, last_name, email, dob)
SET student_id = '$student_id', first_name = '$first_name', last_name = '$last_name', email = '$email', dob = '$dob'
WHERE id = '$id'";
$result = $mysqli->query($sql);
if ($result) {
header('location: index.php');
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Student List</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>
<body>
<div class="card">
<div class="card-body">
<h3 class="card-title">Create Student</h3>
<form method="POST" action="./update.php" id="update">
<!-- Student ID -->
<div class="form-group">
<label for="student_id">Student ID <span style="color:red;">*</span></label>
<input type="text" id="student_id" name="student_id" class="form-control <?php echo isset($errors['student_id']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['student_id'] ?>">
<?php if (isset($errors) && isset($errors['student_id'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['student_id']; ?></small>
<?php } ?>
</div>
<!-- First Name -->
<div class="form-group">
<label for="first_name">First Name <span style="color:red;">*</span></label>
<input type="text" id="first_name" name="first_name" class="form-control <?php echo isset($errors['first_name']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['first_name'] ?> ">
<?php if (isset($errors) && isset($errors['first_name'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['first_name']; ?></small>
<?php } ?>
</div>
<!-- Last Name -->
<div class="form-group">
<label for="last_name">Last name <span style="color:red;">*</span></label>
<input type="text" id="last_name" name="last_name" class="form-control <?php echo isset($errors['last_name']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['last_name'] ?>">
<?php if (isset($errors) && isset($errors['last_name'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['last_name']; ?></small>
<?php } ?>
</div>
<!-- Email -->
<div class="form-group">
<label for="email">Email <span style="color:red;">*</span></label>
<input type="email" id="email" name="email" class="form-control <?php echo isset($errors['email']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['email'] ?> ">
<?php if (isset($errors) && isset($errors['email'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['email']; ?></small>
<?php } ?>
</div>
<!-- Date of Birth -->
<div class="form-group">
<label for="dob">Date of Birth <span style="color:red;">*</span></label>
<input type="date" id="dob" name="dob" class="form-control <?php echo isset($errors['dob']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['dob'] ?> ">
<?php if (isset($errors) && isset($errors['dob'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['dob']; ?></small>
<?php } ?>
</div>
<!-- Buttons -->
<button type="submit" class="btn btn-primary" name="save">Save</button>
<a class="btn btn-secondary" href="./index.php">Cancel</a>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>
Here is some pictures about those:
Hopefully, you can help me solve those problems as much as possible. Thank you!
The date of birth issue: extra space at the end of your value tag
value="<?php echo $students['dob'] ?> "
The database issues:
malformed update statement
insecure, open-to-attack query
You kind of mixed insert and update.
UPDATE students(student_id, first_name, last_name, email, dob)
SET student_id = '$student_id', first_name = '$first_name', last_name = '$last_name', email = '$email', dob = '$dob'
WHERE id = '$id'
Update statements don't take a field list in parens like you have it.
So the statement is failing. However you should really protect again SQL injection attacks by using query binding and prepared statements. Looks like this:
$sql = "UPDATE students SET student_id = '?', first_name = '?', last_name = '?', email = '?', dob = '?' WHERE id = '?'";
$query = $mysqli->prepare($sql);
$query->bind_param("isssi", $student_id, $first_name, $last_name, $email, $dob, $id);
$query->execute();
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Can someone tell me why the <?php echo $userPasswordError; ?> line returns nothing (empty) instead of <div class="invalid-feedback">Too long.</div> when I enter a password which contain more than 1 character with the below code ?
If I change this line : $userPasswordError = '<div class="invalid-feedback">Too long.</div>';
with this $userPasswordError = 'Too long.'; , it works ! Output is "Too long.".
<?php
$user = $userPassword = '';
$userError = $userInvalid = $userPasswordError = $userPasswordInvalid = '';
$isvalidOrInvalidUser = $isvalidOrInvalidUserPassword = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Verify username.
if (!empty($_POST["user"])) {
if (strlen($_POST["user"]) <= 32) {
$user = $_POST["user"];
$userError = '<div class="valid-feedback">Correct.</div>';
$isvalidOrInvalidUser = 'is-valid';
}
else {
$userInvalid = $_POST["user"];
$userError = '<div class="invalid-feedback">Too long.</div>';
$isvalidOrInvalidUser = 'is-invalid';
}
}
else {
$userError = '<div class="invalid-feedback">Please, add username.</div>';
$isvalidOrInvalidUser = 'is-invalid';
}
// Verify password.
if (!empty($_POST["userpassword"])) {
if (strlen($_POST["userpassword"]) <= 1) {
$userPassword = $_POST["userpassword"];
$userPasswordError = '<div class="valid-feedback">Correct.</div>';
$isvalidOrInvalidUserPassword = 'is-valid';
}
else {
$userPasswordInvalid = $_POST["userpassword"];
$userPasswordError = '<div class="invalid-feedback">Too long.</div>';
$isvalidOrInvalidUserPasword = 'is-invalid';
}
}
else {
$userPasswordError = '<div class="invalid-feedback">Please, add password.</div>';
$isvalidOrInvalidUserPassword = 'is-invalid';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="user">Username :</label>
<input type="text" class="form-control <?php echo $isvalidOrInvalidUser; ?>" id="user" name="user" placeholder="User here" value="<?php echo $user.$userInvalid; ?>">
<?php echo $userError; ?>
</div>
<div class="col-md-3 mb-3">
<label for="userpwd">User password :</label>
<input type="password" class="form-control <?php echo $isvalidOrInvalidUserPassword; ?>" id="userpassword" name="userpassword" value="<?php echo $userPassword.$userPasswordInvalid; ?>">
<?php echo $userPasswordError; ?>
</div>
</div>
<button class="btn btn-primary" type="submit">Add</button>
</form>
</body>
</html>
I finally know why.
$userPasswordError = '<div class="invalid-feedback">Too long.</div>';
$isvalidOrInvalidUserPasword = 'is-invalid';
The variable name of isvalidOrInvalidUserPasword is wrong, it should be $isvalidOrInvalidUserPassword (missing an s at Pasword).
If the input does not have class is-invalid, the error message will not visible!
Hope this helps!
I have used header("Content-Type:text/html; charset=utf-8"); & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> on both html & php parts.
But for the webpage contents displayed , the text of the Chinese words are garbled .How to tackle the problem ?
create.php
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=utf-8");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Amount = "";
$CName_err = $Address_err = $Amount_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_CName = trim($_POST["CName"]);
if(empty($input_CName)){
$CName_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z'-.\s ]+$/")))){
$CName_err = 'Please enter a valid name.';
} else{
$CName = $input_CName;
}
// Validate address
$input_Address = trim($_POST["Address"]);
if(empty($input_Address)){
$Address_err = 'Please enter an address.';
} else{
$Address = $input_Address;
}
// Validate Amount
$input_Amount = trim($_POST["Amount"]);
if(empty($input_Amount)){
$Amount_err = "Please enter the amount.";
} elseif(!ctype_digit($input_Amount)){
$Amount_err = 'Please enter a positive integer value.';
} else{
$Amount = $input_Amount;
}
// Check input errors before inserting in database
if(empty($CName_err) && empty($Address_err) && empty($Amount_err)){
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Amount) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName,$Address,$Amount));
Database::disconnect();
header("Location: index.php");
}}
?>
<!DOCTYPE html>
<!--<html lang="en">-->
<head>
<meta http-equiv="Content-Type" content="text/html; 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>捐贈表格</h2>
</div>
<p>本人願意以信用卡捐款</p><br>
<p>I would like to make donation</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($CName_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="CName" class="form-control" value="<?php echo $CName; ?>">
<span class="help-block"><?php echo $CName_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<textarea name="Address" class="form-control"><?php echo $Address; ?></textarea>
<span class="help-block"><?php echo $Address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?>">
<label>Amount</label>
<input type="text" name="Amount" class="form-control" value="<?php echo $Amount; ?>">
<span class="help-block"><?php echo $Amount_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
<p>多謝您的支持</p><br>
<p>Thank you for your support</p>
</div>
</div>
</div>
</div>
</body>
</html>
Update
garbled page :
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'];
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'];