I need help, the problem is that I have a input page (the modified user profile)
where I have a section of addresses and I need to do a loop where each group of inputs I put the information of each of the directions.
Because now for example if I have 3 directions, in the 3 groups of inputs I get the same repeated information...
Here is a part of the code, I don't put all it because is too large, I only put the important code of this issue.
Thanks to all :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" lang="es-es">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="font-awesome-4.5.0/css/font-awesome.min.css"/>
<link href="css/css.css" rel="stylesheet" type="text/css" media="all" />
<link rel="stylesheet" type="text/css" href="css/icSquared_v1.0.css"/>
<title>Modificación de Direcciones</title>
</head>
<body>
<div>
<?php
include 'fn.php';
iniciarSesion();
$email = $_SESSION['user'];
$conexion = conectar();
$sql = "SELECT * FROM DIRECCION WHERE email_c='".$email."'";
if($resultado = $conexion -> query($sql)){
while($fila = mysqli_fetch_array($resultado)){
$ide = $fila[0];
$via = $fila[1];
$nombre = $fila[2];
$numero = $fila[3];
$piso = $fila[4];
$poblacion = $fila[6];
$direcciones = mysqli_num_rows($resultado);
desconectar($conexion);
$sql = "SELECT * FROM POBLACION WHERE idPoblacion='".$poblacion."'";
$conexion = conectar();
if($resultado = $conexion -> query($sql)){
if($fila = mysqli_fetch_array($resultado)){
$codigoPostal = $fila[1];
$nombrePob = $fila[2];
$comunidad = $fila[3];
$pais = $fila[5];
desconectar($conexion);
}
}else{
desconectar($conexion);
}
}else{
deconectar($conexion);
}
?>
<div class="col-sm-8">
<div id="admin_centro" style="margin-top:2%">
<form action="action.php?accion=updateCenterDir" method="post">
<?php for($i=0; $i<$direcciones; $i++){ ?>
<div class="col-sm-2" style="margin:2% 6% 0 5%;">
<div class="form-group">
<input type="hidden" name="ide" value="<?php echo $ide; ?>" />
<h4 class="text-success text-right">Dirección <?php echo $i+1 ?></h4>
<label>Tipo de via:</label>
<input type="text" name="via" class="form-control" value="<?php echo $via; ?>" required />
</div>
<div class="form-group">
<label>Nombre: </label>
<input type="text" name="nombre" class="form-control" value="<?php echo $nombre; ?>" required />
</div>
<div class="form-group">
<label>Numero: <label>
<input type="number" name="num" class="form-control" value="<?php echo $numero; ?>" required min="0"/>
</div>
<div class="form-group">
<label>Piso: <label>
<input type="text" name="piso" class="form-control" value="<?php echo $piso; ?>" />
</div>
<div class="form-group">
<label>Codigo Postal: <label>
<input type="text" name="cp" class="form-control" value="<?php echo $codigoPostal; ?>" required />
</div>
<div class="form-group">
<label>Pais: <label>
<?php desplegable_pais(-1);?>
</div>
<div class="form-group">
<label>Poblacion: <label>
<?php echo $nombrePob." - ".$comunidad." - ".$pais; ?>
<!-- FALTA SELECT DEPENDIENTE-->
</div>
<input class="btn btn-success" type="submit" id="enviar" value="Modificar"/>
</div>
<?php } ?>
</form>
</div>
</div>
</div>
</div>
</body>
<script src="js/jquery-1.12.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/scriptLogin.js"></script>
</html>
elseif($action == "updateCenterDir"){
$ide = $_POST['ide'];
$via = $_POST['via'];
$nombre = $_POST['nombre'];
$numero = $_POST['num'];
$piso = $_POST['piso'];
$cp = $_POST['cp'];
$poblacion = $_POST['poblacion'];
$conexion = conectar();
$sql = "UPDATE DIRECCION SET via='".$via."', nombre='".$nombre."', numero=".$numero.", piso='".$piso."', codigoPostal='".$cp."', poblacion='".$poblacion."' WHERE idInstalacion=".$ide;
if($resultado = $conexion -> query($sql)){
header("Location:mod_infoDir.php?miss=1");
desconectar($conexion);
}else{
header("Location:mod_infoDir.php?miss=2");
desconectar($conexion);
}
}
You should generate the form fields from inside the while loop, and you do that but not the right way.
Right now, your while loop is closed before the form.
if($resultado = $conexion -> query($sql)){
$direcciones = mysqli_num_rows($resultado);
while($fila = mysqli_fetch_array($resultado)){
$ide = $fila[0];
$via = $fila[1];
$nombre = $fila[2];
$numero = $fila[3];
$piso = $fila[4];
$poblacion = $fila[6];
$sql = "SELECT * FROM POBLACION WHERE idPoblacion='" . $poblacion . "'";
if($resultado = $conexion -> query($sql)){
if($fila = mysqli_fetch_array($resultado)){
$codigoPostal = $fila[1];
$nombrePob = $fila[2];
$comunidad = $fila[3];
$pais = $fila[5];
}
}
?>
Generate divs here...
<?php
} // close while($fila = mysqli_fetch_array($resultado))
} // close if($resultado = $conexion -> query($sql))
?>
Move the last disconnect after the divs that generate the form.
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
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"]) : '';
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 have been playing around with editing user profiles (Logged in as) which is working just fine.
So I decided to try editing other users profiles by populating a table with users (which works fine and also has, ban & delete working fine), clicking a hyperlink with id (which works fine), showing the username of the profile and their current profile info(which works fine) and a form to update which is identical to the edit session user form(also, works fine).
But when submitting, it does not update the record.
I am using $userID = $_GET['id']; and also binding that to sql select id command.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once '../includes/conn.php';
if(!$user->is_loggedin()){
$user->redirect('../users/login.php');
}
$userID = $_GET['id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$userID));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if (isset($_POST['update'])) {
$location = isset($_POST['location']) ? $_POST['location'] : null;
$about = isset($_POST['about']) ? $_POST['about'] : null;
$title = isset($_POST['title']) ? $_POST['title'] : null;
$sql_part = array();
$prepare = array();
if ($location) {
$sql_part[] = 'location = :location';
$prepare[':location'] = $location;
}
if ($about) {
$sql_part[] = 'about = :about';
$prepare[':about'] = $about;
}
if ($title) {
$sql_part[] = 'title = :title';
$prepare[':title'] = $title;
}
$prepare[':id'] = $userID;
if (count($sql_part)) {
$sql = 'UPDATE users SET ';
$sql .= implode(', ', $sql_part);
$sql .= ' WHERE id = :id';
$stmt = $conn->prepare($sql);
if ($stmt) {
$result = $stmt->execute($prepare);
$count = $stmt->rowCount();
header('Location: '. $_SERVER['REQUEST_URI']);
exit;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>EpicOwl UK | CMS Users Edit Profile</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</ul>
</div>
</div>
<div id="content">
<form method="post"><br />
<h2>Edit <?php echo ($userRow['username']); ?>'s Profile</h2>
<label><strong>User Title:</strong></label><br />
<input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
<label><strong>My Location:</strong></label><br />
<input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
<label><strong>About Me:</strong><label><br />
<textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
<button type="submit" name="update">Update</button><br /><br /><br />
</form>
</div>
<div id="footer">
<p class="copyright">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
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'];