I have an html form set to submit to itself with $SERVER['PHP_SELF'] but the form does not seem to be able submit, instead it simply returns the same form when I click submit (with and input of type submit.
NOTE: the actual code is too long to post here, and I've included all that I think is necessary. The form in question is actually a duplicate of another (which works perfectly) but this one doesn't.
EDIT: I was advised to eventually post the code
SECOND EDIT: I actually removed the tag enctype='multipart/formdata' on the form tag, and the code script now works. But, I need that enctype to be able upload the images. Does anyone know how I can work around that?
<?php
include 'templates/inc/header.php';
include 'templates/inc/system_helpers.php';
include 'config/config.php';
?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ob_start();
$listing_saved = FALSE;
if (isset($_POST['submit'])) {
// property type
$property_type = isset($_POST['property_type']) ? $_POST['property_type'] : '';
// property details
$area_sq = isset($_POST['area_sq']) ? $_POST['area_sq'] : '';
$location = isset($_POST['ex_location']) ? $_POST['ex_location'] : '';
$bedrooms = isset($_POST['bedrooms']) ? $_POST['bedrooms'] : '';
$bathrooms = isset($_POST['bathrooms']) ? $_POST['bathrooms'] : '';
$furnished = isset($_POST['furnished']) ? $_POST['furnished'] : '';
// additional information
$description = isset($_POST['description']) ? $_POST['description'] : '';
$garden = isset($_POST['garden']) ? $_POST['garden'] : '';
$pool = isset($_POST['pool']) ? $_POST['pool'] : '';
$flatlet = isset($_POST['flatlet']) ? $_POST['flatlet'] : '';
$garage = isset($_POST['garage']) ? $_POST['garage'] : '';
$parking = isset($_POST['parking']) ? $_POST['parking'] : '';
$parking_spaces = isset($_POST['parking_sapces']) ? $_POST['parking_spaces'] : '';
// pricing
$price = isset($_POST['price']) ? $_POST['price'] : '';
// contact person
$first_name = isset($_POST['f_name']) ? $_POST['f_name'] : '';
$last_name = isset($_POST['l_name']) ? $_POST['l_name'] : '';
$email_address = isset($_POST['email_address']) ? $_POST['email_address'] : '';
$phone = isset($_POST['phone']) ? $_POST['phone'] : '';
$physical_address = isset($_POST['physical_address']) ? $_POST['physical_address'] : '';
$region = isset($_POST['region']) ? $_POST['region'] : '';
// legal consent
$consent = isset($_POST['consent']) ? $_POST['consent'] : '';
$isFNBBanked = isset($_POST['isFNBBanked']) ? $_POST['isFNBBanked'] : '';
$account_holder = isset($_POST['account_holder']) ? $_POST['account_holder'] : '';
$account_number = isset($_POST['account_number']) ? $_POST['account_number'] : '';
$commercialAcceptance = isset($_POST['commercialAcceptance']) ? $_POST['commercialAcceptance'] : '';
$isInfoCorrect = isset($_POST['isInfoCorrect']) ? $_POST['isInfoCorrect'] : '';
$optionToOptOut = isset($_POST['optionToOptOut']) ? $_POST['optionToOptOut'] : '';
$isAuthorized = isset($_POST['isAuthorized']) ? $_POST['isAuthorized'] : '';
// create an uploads directory
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR, 0777, true);
}
/*
* List of file names to be filled in by the upload script
* below and to be saved in the db table "images" afterwards.
*/
$file_names_to_save = [];
$allowed_mime_types = explode(',', UPLOAD_ALLOWED_MIME_TYPES);
// capture the image uploads
if (!empty($_FILES)) {
if (isset($_FILES['images']['error'])) {
foreach ($_FILES['images']['error'] as $uploadedFileKey => $uploadedFileError) {
if ($uploadedFileError === UPLOAD_ERR_NO_FILE) {
$errors[] = 'You did not provide any files.';
} elseif ($uploadedFileError === UPLOAD_ERR_OK) {
$uploadedFileName = basename($_FILES['images']['name'][$uploadedFileKey]);
if ($_FILES['images']['size'][$uploadedFileKey] <= UPLOAD_MAX_FILE_SIZE) {
$uploadedFileType = $_FILES['images']['type'][$uploadedFileKey];
$uploadedFileTempName = $_FILES['images']['tmp_name'][$uploadedFileKey];
$uploadedFilePath = rtrim(UPLOAD_DIR, '/') . '/' . $uploadedFileName;
if (in_array($uploadedFileType, $allowed_mime_types)) {
if (!move_uploaded_file($uploadedFileTempName, $uploadedFilePath)) {
$errors[] = 'The file "' . $uploadedFileName . '" could not be uploaded.';
} else {
$file_names_to_save[] = $uploadedFilePath;
}
} else {
$errors[] = 'The extension of the file "' . $uploadedFileName . '" is not valid. Allowed extensions: JPG, JPEG, PNG, or GIF.';
}
} else {
$errors[] = 'The size of the file "' . $uploadedFileName . '" must be of max. ' . (UPLOAD_MAX_FILE_SIZE / 1024) . ' KB';
}
}
}
}
}
if (!isset($errors)) {
// add captured data into database
$query = 'INSERT INTO property (
propertytype_id,
land_area,
ex_location,
bedrooms,
bathrooms,
is_furnished,
short_desc,
has_garden,
has_pool,
has_flatlet,
has_parking,
parking_spaces,
price)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
//prepare the statement
$stmt = $connection->prepare($query);
//bind the parameters
$stmt->bind_param('iisiissssssii', $property_type, $area_sq, $location, $bedrooms, $bathrooms, $furnished, $description, $garden, $pool, $flatlet, $parking, $parking_spaces);
//execute the statement
$stmt->execute();
//grab the last car insert ID
$last_insert_id = $connection->insert_id;
// insert into persons table
$persons_sql = 'INSERT INTO person (
property_id,
firstname,
lastname,
email_address,
phone,
city,
region)
VALUES (?, ?, ?, ?, ?, ?, ?)';
$stmt = $connection->prepare($persons_sql);
$stmt->bind_param('isssiss', $last_insert_id, $first_name, $last_name, $email_address, $phone, $physical_address, $region);
$stmt->execute();
// grab the last person's id
$last_person_insert = $connection->insert_id;
// insert into legal table
$legal_sql = 'INSERT INTO legal (
person_id,
consent,
isFNBBanked,
account_holder,
account_number,
commercialAcceptance,
isInfoCorrect,
optionToOptOut,
isAuthorized
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)';
$stmt = $connection->prepare($legal_sql);
$stmt->bind_param('isssissss', $last_person_insert, $consent, $isFNBBanked, $account_holder, $account_number, $commercialAcceptance, $isInfoCorrect, $optionToOptOut, $isAuthorized);
$stmt->execute();
// close the statement
$stmt->close();
// save a record for each uploaded file
foreach ($file_names_to_save as $file_name) {
$query = 'INSERT INTO images (
property_id,
image_name)
VALUES (?, ?)';
$stmt = $connection->prepare($query);
$stmt->bind_param('is', $last_insert_id, $file_name);
$stmt->execute();
$stmt->close();
}
$listing_saved = TRUE;
}
}
?>
<!-- Page Contents -->
<div class="form-container">
<div class="sticky-anchor"></div>
<div class="banner">
<img src="./assets/MarketSquare banner for PROPERTY.jpg" alt="Market Square Form Banner">
</div>
<?php display_message(); ?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" enctype="multipart/form-data">
<!-- PROPERTY DETAILS -->
<div class="section-one">
<h3>Property Details</h3>
<div class="text-fields">
<div class="extra-fields">
<select name="property_type" id="property-type" class="select">
<option value="0">Property Type</option>
<?php
$query = mysqli_query($connection, "SELECT * FROM property_type");
if (mysqli_num_rows($query)) {
$i = 0;
while ($propertytype = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $propertytype['propertytype_id']; ?>"><?php echo $propertytype['type_name']; ?></option>
<?php
$i++;
}
}
?>
</select>
</div>
</div>
<div class="text-fields">
<div class="extra-fields">
<input type="text" name="area_sq" placeholder="Area (in square metres)" required>
<input type="text" name="location" placeholder="Location (e.g. Veki's Village, Mountain Drive, Mbabane)">
</div>
</div>
<div class="text-fields selected">
<div class="extra-fields">
<input type="text" name="bedrooms" placeholder="No. of Bedrooms" required>
<input type="text" name="bathrooms" placeholder="No. of Bathrooms">
</div>
</div>
<label class="check-box">Furnished
<input type="checkbox" name="furnished" value="Yes">
<span class="checkmark"></span>
</label>
</div>
<!-- ADDITIONAL INFORMATION -->
<div class="section-two">
<h3>
Additional Information
<span> (Provide details about additional features)</span>
</h3>
<div class="extra-fields">
<textarea name="description" id="description" cols="30" rows="4" placeholder="Separate your items with a comma ( , )"></textarea>
</div>
External Features <span>(tick where appropriate)</span>
<div class="checks">
<label class="check-box">Garden
<input type="checkbox" name="garden" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Swimming Pool
<input type="checkbox" name="pool" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Bedsitter/flatlet
<input type="checkbox" name="flatlet" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Garage
<input type="checkbox" name="garage" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Open Parking
<input type="checkbox" name="parking" value="Available" id="parking-space" onclick="show_input()">
<span class="checkmark"></span>
</label>
<input type="text" name="parking_spaces" id="parking" placeholder="Number of parking spaces">
</div>
<div class="file-input">
Photos: <span>(max. 12, in all angles incl. interior)</span>
<input type="file" name="images[]" accept=".jpg, .jpeg, .png, .gif, .webp" id="imgUpload" multiple required>
</div>
</div>
<!-- PRICING -->
<div class="section-two pricing">
<h3>
Give it a Price
<span>(The sale price you wish to attach, based on the Valuation Report)</span>
</h3>
<div class="extra-fields">
<input type="text" name="price" placeholder="E " required>
</div>
</div>
<!-- CONTACT PERSON -->
<div class="section-three">
<h3>Contact Person</h3>
<div class="text-fields">
<div class="extra-fields">
<input type="text" name="f_name" placeholder="First name" required>
<input type="text" name="l_name" placeholder="Last name">
</div>
</div>
<div class="text-fields">
<div class="extra-fields">
<input type="email" name="email_address" placeholder="Email address">
<input type="text" name="phone" placeholder="Phone number" required>
</div>
</div>
<div class="text-fields">
<div class="extra-fields">
<input type="text" name="physical_address" placeholder="Town/city (e.g. Lobamba)">
<input type="text" name="region" placeholder="Region (e.g. Hhohho)" required>
</div>
</div>
</div>
<!-- LEGAL -->
<div class="section-four">
<h3>Legal</h3>
<div class="consent">
<input type="checkbox" name="consent" value="Given" required>
I/We give
</div>
<div class="consent">
<input type="checkbox" name="consent_1" value="Yes" required>
I/We confirm .
<div class="extra-fields">
<input type="text" name="acount_name" placeholder="Account Name">
<input type="text" name="account_number" placeholder="Account Number" required>
</div>
</div>
<div class="consent">
<input type="checkbox" name="consent_3" value="Accepted" required>
I/We agree .
</div>
<div class="consent">
<input type="checkbox" name="consent_4" value="Confirmed" required>
I/We confirm
</div>
<div class="consent">
<input type="checkbox" name="consent_5" value="Acknowledged" required>
I/We acknowledge
</div>
<div class="consent">
<input type="checkbox" name="consent_6" value="Confirmed" required>
authorised.
</div>
</div>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if ($listing_saved) {
redirect('listings_Properties.php', 'Your submition has been received. Please give us time to verify validity of the provided information.', 'sucess');
}
?>
</div>
<?php include 'templates/inc/footer.php' ?>
code for the redirect script is
<?php
function redirect($page = FALSE, $message = NULL, $message_type = NULL){
if(is_string($page)){
$location = $page;
}
else{
$location = $_SERVER['SCRIPT_NAME'];
}
// check for message
if($message != null){
$_SESSION['message'] = $message;
}
// check for message type
if($message_type != null){
$_SESSION['message_type'] = $message_type;
}
//...then redirect
header('Location: '. $location);
exit;
}
// display the message
function display_message(){
if(!empty($_SESSION['message'])){
$message = $_SESSION['message'];
if(!empty($_SESSION['message_type'])){
$message_type = $_SESSION['message_type'];
if($message_type == 'error'){
echo '<div class="alert alert-danger" id="msg">'.$message.'</div>';
}
else{
echo '<div class="alert alert-success" id="msg">'.$message.'</div>';
}
}
unset($_SESSION['message']);
unset($_SESSION['message_type']);
}
else{
echo '';
}
}
Thank you to everyone who contributed towards me figuring out what really the problem.
What I didn't realize was that the max file upload in the script is set to 2MB while I was uploading images larger than 2MB, and my error handler wasn't working to actually prompt that. Again thank you to everyone who had suggestions. They really helped me figure out each step
Related
i have a little problem.
i have a contact-form and want to update my database with a crud.
My Contact-Form:
<!-- UPDATE -->
<div class="page-wrapper bg-gra-01 p-t-180 p-b-100 font-poppins">
<div class="container">
<?php
if(isset($_GET['edit'])):
$result = $crud->getMember($_GET['edit']);
?>
<hr />
<div class="row mt-5">
<h3> UPDATE </h3>
<form method="post" action="formprocess.php" class="col-12" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="vorname" value="<?= $result['vorname']; ?>">
</div>
<div class="form-group">
<label>Foto</label>
<input type="file" class="form-control" name="Foto">
</div>
<div class="form-group">
<input type="text" name="birthday" value="<?= $result['birthday']; ?>">
</div>
<div class="form-group">
<h5> Geschlecht </h5>
<select name="Geschlecht">
<option value=""> </option>
<option value=" Männlich" <?php if($result['Geschlecht'] == 'Männlich'){ ?> selected <?php } ?>> Männlich </option>
<option value=" Weiblich" <?php if($result['Geschlecht'] == 'Weiblich'){ ?> selected <?php } ?>> Weiblich </option>
<option value="Divers" <?php if($result['Geschlecht'] == 'Divers'){ ?> selected <?php } ?>> Divers </option>
</select>
</div>
<div class="input-group">
<input class="input--style-3" type="email" placeholder="Max-Mustermann#gmail.com" name="email" value="<?= $result['email'];?>">
</div>
<div class="input-group">
<input class="input--style-3" type="text" placeholder="01575 2234455" name="phone" value="<?= $result['phone'];?>">
</div>
<p> <input type="hidden" name="ID" value="<?= $result['ID']; ?>">
<p> <input type="submit" class="btn btn-outline-Success" name="update" Value="Update"> </p>
</form>
</div>
<?php
endif;
?>
My formprocess:
if(isset($_POST['update'])) {
if(isset($_POST['vorname']) && !empty($_POST['vorname']) &&
isset($_FILES['Foto']) && !empty($_FILES['Foto']) &&
isset($_POST['Geschlecht']) && !empty($_POST['Geschlecht']) &&
isset($_POST['birthday']) && !empty($_POST['birthday']) &&
isset($_POST['phone']) && !empty($_POST['phone']) &&
isset($_POST['email']) && !empty($_POST['email']) &&
isset ($_POST['ID']) && !empty($_POST['ID'])
){
$vorname = $_POST['vorname'];
$pfad = "upload/";
$filename = $_FILES['Foto'] ['tmp_name'];
$name = $pfad . time() . "-" . $_FILES['Foto'] ['name'];
$Geschlecht = $_POST['Geschlecht'];
$birthday = $_POST ['birthday'];
$phone = $_POST ['phone'];
$email = $_POST['email'];
$ID = $_POST ['ID'];
if(move_uploaded_file($filename,$name)){
if($crud->updateMember($ID, $vorname, $name, $Geschlecht, $birthday, $phone, $email)) {
$_SESSION['msg-class'] = "success";
$_SESSION['msg'] = "Update war erfolgreich!";
header('location: Admin.php');
} else{
$_SESSION['msg-class'] = "danger";
$_SESSION['msg'] = "Es ist ein Fehler aufgetreten!";
header('location: Admin.php');
}
}
}
}
My crud.php:
public function updateMember($ID, $vorname, $Foto, $Geschlecht, $birthday, $phone, $email) {
$stmt = $this->conn->prepare("UPDATE testing SET vorname = :vorname, Foto = :Foto, Geschlecht = :Geschlecht, birthday = :birthday, phone = :phone, email = :email WHERE ID=:ID");
$erg = $stmt->execute(array(
':vorname' => $vorname,
':Foto' => $Foto,
':Geschlecht' => $Geschlecht,
':birthday' => $birthday,
':phone' => $phone,
':email:' => $email,
':ID' => $ID
));
return $erg;
If i press the Update button i get that error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\classes\crud.php:51 Stack trace: #0 C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\classes\crud.php(51): PDOStatement->execute(Array) #1 C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\formprocess.php(66): Crud->updateMember('12', 'Boris', 'upload/16693640...', ' Weiblich', '0000-00-01', '666', 'b#web.de') #2 {main} thrown in C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\classes\crud.php on line 51
i don't know why, can anyone help?
i got the solution...
my code was apparently "unsorted". For example, I had the birthday in the 3rd place, but entered it as a 4th in the code
I'm not a PHP specialist, but I think your values and DB columns count mismatch. From the exception, I see that you have an invalid parameter number. You can post the whole file so we can debug it together.
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
I have a script that was working perfectly but I cannot see the error. The script has two functions. The first is to create a new client in the database, which works perfectly. The second part of the script (near the bottom) is to update the database for the client if they exist.
The page sends the client ID to make the edits, but somewhere is this script it stops responding. When submitted, the view-client.php page loads, but the URL displays 'client=Array', not for example 'client=1'. I think I have narrowed it down to the PHP that controls the new password entered on registration, both called $password and $passKey.
This is meant to save the updated data to the database and redirect the user upon submit to the view-client.php page with the correct ID. Any help is greatly appreciated!
EDIT
Form and script for reference...
<?PHP
include('../core/init.php');
require_once('dbConfig.php');
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 5; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
//$generatedId = "SPI-E7HN2SBIIF5W";
$generatedId = 'SPI-'.$randomString;
//Prepare select query
$statement = $db->prepare("SELECT client_unique_id FROM clients WHERE client_unique_id = ? LIMIT 1");
//Determine variable and then bind that variable to a parameter for the select query ?
$id = $generatedId;
$statement->bind_param('s', $id);
//Execute and store result so that num_rows returns a value and not a 0
$statement->execute();
$statement->store_result();
//Bind result to a variable for easy management afterwards
$statement->bind_result($clientId);
// Generate a random ID for the user if the previously generated one already exists
if($statement->num_rows > 0) {
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 0; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$generatedId = 'SPI-'.$randomString;
//echo $generatedId;
}
$client = $_POST['createClientId'];
$insertId = $_POST['insertId'];
$passKey = $_POST['PassKey'];
$firstName = $_POST['FirstName'];
$surname = $_POST['Surname'];
$businessName = $_POST['BusinessName'];
$addressLine1 = $_POST['AddressLine1'];
$addressLine2 = $_POST['AddressLine2'];
$townCity = $_POST['TownCity'];
$county = $_POST['County'];
$postcode = $_POST['Postcode'];
$telephone = $_POST['Telephone'];
$mobile = $_POST['Mobile'];
$userName = $_POST['Username'];
$accountType = $_POST['AccountType'];
$email = $_POST['EmailAddress'];
$password = $_POST['Password'];
$additionalInfo = $_POST['AdditionalInformation'];
foreach($passKey as $key => $val) {
if($password[$key] == '' || !$password[$key]){
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 18; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$generatedPassword = $randomString;
/* Two create a Hash you do */
$password = $bcrypt->genHash($generatedPassword);
//$password = sha1($generatedPassword);
} else {
$password = $bcrypt->genHash($password[$key]);
//$password = sha1($password[$key]);
}
if(!$client[$key]) {
if($_SESSION['member_unique_id']=="supermember") {
$member_unique_ids="ISPI-ADMIN";
} else {
$member_unique_ids = $_SESSION['member_unique_id'];
}
if ($stmt = $db->prepare("INSERT clients (client_id, member_unique_id, client_unique_id, client_key, client_first_name, client_last_name, client_organisation_name, client_business_type, client_username, client_address_line_1, client_address_line_2, client_town, client_county, client_postcode, client_telephone, client_mobile, client_email_address, client_password, client_additional_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
$stmt->bind_param("sssssssssssssssssss", $insertId, $member_unique_ids, $generatedId, $passKey[$key], $firstName[$key], $surname[$key], $businessName[$key], $accountType[$key], $userName[$key], $addressLine1[$key], $addressLine2[$key], $townCity[$key], $county[$key], $postcode[$key], $telephone[$key], $mobile[$key], $email[$key], $password, $additionalInfo[$key]);
$stmt->execute();
$stmt->close();
echo $db->insert_id;
} else {
echo "ERROR: Could not prepare Insert SQL statement.";
}
} else {
if ($stmt = $db->prepare("UPDATE clients SET client_first_name = ?, client_last_name = ?, client_organisation_name = ?, client_business_type = ?, client_username = ?, client_address_line_1 = ?, client_address_line_2 = ?, client_town = ?, client_county = ?, client_postcode = ?, client_telephone = ?, client_mobile = ?, client_email_address = ?, client_additional_info = ? WHERE client_id = ?")) {
$stmt->bind_param("ssssssssssssssi", $firstName[$key], $surname[$key], $businessName[$key], $accountType[$key], $userName[$key], $addressLine1[$key], $addressLine2[$key], $townCity[$key], $county[$key], $postcode[$key], $telephone[$key], $mobile[$key], $email[$key], $additionalInfo[$key], $client);
$stmt->execute();
$stmt->close();
echo $client;
} else {
echo "ERROR: Could not prepare Update SQL statement.";
}
}
}
<head>
<!--START-->
<?PHP include('../layout/start.php'); ?>
<!--/START-->
<script>
$(document).ready(function(){
function editClient(form) {
var $this = $(form);
var string = $this.serialize();
$.ajax({
type: "POST",
url: "../includes/db-edit-client.php",
data: string,
cache: false,
success: function(data){
setTimeout(function () {
window.location = "view-client.php?member=<?=$member_unique_id?>&client="+data;
}, 0);
}
});
}
$('body').on('click', '#updateClientDetails', function(e) {
editClient("#editClientForm");
});
});
</script>
</head>
<body>
<!--MAIN ELEMENTS-->
<?PHP include('../layout/header.php'); ?>
<?PHP include('../layout/menu.php'); ?>
<div class="pageWrapper shrink">
<div class="pageContainer">
<!--/MAIN ELEMENTS-->
<!--START FORM-->
<form id="editClientForm">
<input type="hidden" name="createClientId[]" value="<?=$_GET['client']?>">
<input type="hidden" name="PassKey[]">
<div class="titleBox clientBlue">
Edit Client - <?=$client_organisation_name?>
<button id="updateClientDetails" class="mainButton clientBlue">Update Client</button>
</div>
<div class="breadcrumbs">
<ul id="breadcrumbsList">
<li>Home</li>
<li>Clients</li>
<li>Edit Client - <?=$client_organisation_name?></li>
</ul>
</div>
<!--TABLE-->
<div class="tableContainer">
<div class="tableHeader clientBlue">
<div class="col12 colNoPaddingLeft">Client Details</div>
</div>
<div class="tableBody">
<div class="rowTight">
<div class="col3 colNoPaddingLeft"><input type="text" class="formInput" name="FirstName[]" placeholder="First name" autocomplete="off" value="<?=$client_first_name?>"></div>
<div class="col3"><input type="text" class="formInput" name="Surname[]" placeholder="Surname" autocomplete="off" value="<?=$client_last_name?>"></div>
<div class="col3"><input type="text" class="formInput" name="BusinessName[]" placeholder="Business name" autocomplete="off" value="<?=$client_organisation_name?>"></div>
<div class="col3 colNoPaddingRight"><input type="text" class="formInput" name="Username[]" placeholder="Username" autocomplete="off" value="<?=$client_username?>"></div>
</div>
</div>
</div><!--END TABLE-->
<!--TABLE-->
<div class="tableContainer">
<div class="tableHeader clientBlue">
<div class="col12 colNoPaddingLeft">Contact Details</div>
</div>
<div class="tableBody">
<div class="rowTight">
<div class="col3 colNoPaddingLeft"><input type="text" class="formInput" name="AddressLine1[]" placeholder="Address line 1" autocomplete="off" value="<?=$client_address_line_1?>"></div>
<div class="col3"><input type="text" class="formInput" name="AddressLine2[]" placeholder="Address line 2" autocomplete="off" value="<?=$client_address_line_2?>"></div>
<div class="col3"><input type="text" class="formInput" name="TownCity[]" placeholder="Town/city" autocomplete="off" value="<?=$client_town?>"></div>
<div class="col3 colNoPaddingRight"><input type="text" class="formInput" name="County[]" placeholder="County" autocomplete="off" value="<?=$client_county?>"></div>
</div>
<div class="rowTight">
<div class="col3 colNoPaddingLeft"><input type="text" class="formInput" name="Postcode[]" placeholder="Postcode" autocomplete="off" value="<?=$client_postcode?>"></div>
<div class="col3"><input type="text" class="formInput" name="Telephone[]" placeholder="Telephone" autocomplete="off" value="<?=$client_telephone?>"></div>
<div class="col3"><input type="text" class="formInput" name="Mobile[]" placeholder="Mobile" autocomplete="off" value="<?=$client_mobile?>"></div>
<div class="col3 colNoPaddingRight"> </div>
</div>
</div>
</div><!--END TABLE-->
<!--TABLE-->
<div class="tableContainer">
<div class="tableHeader clientBlue">
<div class="col12 colNoPaddingLeft">Account Details</div>
</div>
<div class="tableBody">
<div class="rowTight">
<div class="col3 colNoPaddingLeft">
<select name="AccountType[]" class="formDropdown">
<option value="Business type" selected>Business type</option>
<?php
$types = array('Landlord', 'Tenant', 'Letting agent', 'Estate agent', 'Surveyors', 'Insurance', 'Other');
foreach ($types as $type) {
$selected = $client_business_type == $type ? ' selected="selected"' : null;
echo '<option value="'.$type.'"'.$selected.'>'.$type.'</option>';
}
?>
</select>
</div>
<div class="col3"><input type="email" class="formInput" name="EmailAddress[]" placeholder="Email address" autocomplete="off" value="<?=$client_email_address?>"></div>
<div class="col3"><textarea placeholder="Additional information" name="AdditionalInformation[]" class="formInput"><?=$client_additional_info?></textarea></div>
<div class="col3 colNoPaddingRight"> </div>
</div>
</div>
</div><!--END TABLE-->
</form><!--END FORM-->
</div><!--END PAGE CONTAINER-->
</div><!--END PAGE WRAPPER-->
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'];
I've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far.
PHP CODE:
<?php
require 'database.php';
if ( !empty($_POST)) {
$iError = null;
$nError = null;
$dError = null;
$tError = null;
$id = $_POST['id'];
$name = $_POST['name'];
$Address = $_POST['Address'];
$phone = $_POST['phone'];
$valid = true;
if (empty($id)) {
$iError = 'add id';
$valid = false;
}
if (empty($name)) {
$nError = 'add name';
$valid = false;
}
if (empty($Address)) {
$dError = 'add address';
$valid = false;
}
if (empty($phone)) {
$tError = 'add phone';
$valid = false;
}
if ($valid) {
$tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)";
$arr1 = array($id, $name, $Address, $phone);
$stmt = sqlsrv_query($conn, $tsql, $arr1 );
if ( $stmt === FALSE ){
echo "New data created";
}
else {
echo "Error creating data";
die(print_r(sqlsrv_errors(),true));
}
}
}?>`
this is the HTML part:
<body>
<div>
<div>
<h3>CREAR</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class=" <?php echo !empty($iError)?'error':'';?>">
<label >ID</label>
<div >
<input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>">
<?php if (!empty($iError)): ?>
<span ><?php echo $iError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($nError)?'error':'';?>">
<label>name</label>
<div>
<input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nError)): ?>
<span><?php echo $nError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($emailError)?'error':'';?>">
<label >Address</label>
<div >
<input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>">
<?php if (!empty($dError)): ?>
<span><?php echo $dError;?></span>
<?php endif;?>
</div>
</div>
<div class=" <?php echo !empty($tError)?'error':'';?>">
<label >phoner</label>
<div >
<input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>">
<?php if (!empty($tError)): ?>
<span ><?php echo $tError;?></span>
<?php endif;?>
</div>
</div>
<div >
<button type="submit">Create</button>
Return
</div>
</form>
</div>
</div>