I am trying to put the form results into a database but it is not working properly. No errors seem to be happening, what is wrong with my code?
This is my first page with the booking form:
$booking_sql = "SELECT * FROM calendar, missions WHERE calendar_id = '%d' AND calendar.missions_id = missions.missions_id" ;
$_SESSION['booking']['calendar'];
$booking_query = mysqli_query($dbconn, $booking_sql) or die(mysqli_error());
$rsBooking = mysqli_fetch_assoc($booking_query);
?>
<form action="confirm.php" method="post" name="fmNumCon" id="fmNumCon">
<div class="row"><span class="label"><strong class="full"></strong></span> <span class="element"><h4><?php echo $rsBooking['missions_name'].', '.$rsBooking['calendar_date']; ?></h4></span></div>
<div class="row"><span class="label"><h4>*Number of people:</h4></span><span class="element">
<select name="number" id="number" onchange="getNumber()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</span></div>
<!-- <div class="row"><span class="label"</span><span class="element"><h4>$NZDisplay cost per person.00</h4><input type="hidden" name="price" id ="price" value="" /></span></div>
<div class="row"><span class="label"> </span><span class="element">
<a id="update" href="booking.php?mode=update">Update cost</a>
</span></div> -->
<div class="row"><strong class="full"><h4>Conatact details:</h4></strong> </div>
<div class="row">
<input name="name" type="text" id="name" value="<?= isset($name) ? $name : ''?>" placeholder="name"/>
</div>
<div class="row">
<input name="$phone" type="text" id="phone" placeholder="phone" value="<?= isset($phone) ? $phone : ''?>"/>
</div>
<div class="row">
<input name="email" type="text" id="email" placeholder="email" value="<?= isset($email) ? $email : ''?>"/>
</div>
<div class="row">
<input type="reset" name="Reset" value="Reset" />
<input type="submit" name="Submit" value="Continue" />
</div>
</form>
Here is the confirm page below:
$number = $_SESSION['booking']['number'];
$phone = $_POST['phone'];
$email = $_POST['email'];
require_once('includes/dbconn.php');
$booking_sql = sprintf("SELECT * FROM calendar, missions WHERE calendar_id = '%d' AND calendar.missions_id = missions.missions_id", $_SESSION['booking']['calendar']);
$booking_query = mysqli_query($dbconn, $booking_sql) or die(mysqli_error());
$rsBooking = mysqli_fetch_assoc($booking_query);
?>
<form action="thanks.php" method="post" name="fmConfirm" id="fmConfirm" display="hidden">
<div class="row"><?php echo $rsBooking['missions_name']; ?></div>
<div class="row"><input type="hidden" name="number" value ="<?php echo $number?>"></input></div>
<div class="row"><input type="hidden" name="name" value ="<?php echo $name?>"></input></div>
<div class="row"><input type="hidden" name="phone" value ="<?php echo $phone?>"></input></div>
<div class="row"><input type="hidden" name="email" value ="<?php echo $email?>"></input></div>
<div class="row"><span class="label"> </span> <span class="element">Edit details</span></div>
<div class="row"><span class="label"> </span><span class="element">
<input type="submit" name="Submit" value="Finsih" />
</span></div>
</form>
Here is my thanks page:
<?php require_once('includes/dbconn.php'); ?>
<?php session_start();
$date = date('Y-m-d');
// $calendar = $_POST['calendar_date'];
$name = $_POST['name'];
$number = $_POST['number'];
$phone = $_POST['phone'];
$email = $_POST['email'];
// $booking_sql = "INSERT into bookings (calendar_id, booking_name,
// booking_number, booking_phone,
// booking_email, booking_date) VALUES ('$calendar','$name', 'number', 'phone', 'email')";
$booking_sql = "INSERT INTO bookings (booking_name,
booking_number, booking_phone,
booking_email, booking_date)
VALUES ('$name','$number','$phone','$date')";
$dbconn->query($booking_sql);
// $sql = "INSERT INTO bookings (booking_fname, booking_lname, booking_email, user_id, date_id)
// VALUES ('$fName','$lName','$email', '$userid', '$dateid')";
// $dbc->query($sql);
$booking_query = mysqli_query($dbconn, $booking_sql);
$_SESSION = array();
// session_destroy();
// if(!isset($_COOKIE['active'])) {
// setcookie('active', 'no', time() + 31536000);
// }
?>
<h2>Booking complete </h2>
<p> </p>
<p>Thank you for choosing <strong>Mountain Bike Missions</strong>.</p>
<p>To check your booking immediately, you can log in with your email address here. At any another time, please use the <strong>Check booking</strong> link in the <strong>Booking</strong> section of the site.</p>
I adjusted your thanks.php a little.
throughout your other scripts you used the procedural syntax of mysqli, in thanks.php you switched to object-syntax
removed all those commented lines
session_start() should always be on top of the program (after ini-directives), if you have in an included file some output by accident it would cause a fatal error otherwise
I used prepared statemnts to work with the data you get from users, this way the formatting of the query can not be broken if there are special characters in the input
enabled display_errors so you get shown your errors (when you are done testing you can remove those lines, you don't want to show technical errormessages to users when going productive)
used trigger_error to catch errors thrown by the database to treat them like php errors
Code looks like this:
<?php
/*
* enable display_errors
*/
ini_set('display_errors', 1);
error_reporting(-1);
/*
* start session, construct connection to db
*/
session_start();
require_once('includes/dbconn.php');
/*
* define your variables
*/
$date = date('Y-m-d');
$name = $_POST['name'];
$number = $_POST['number'];
$phone = $_POST['phone'];
$email = $_POST['email'];
/*
* define your sql-statemnt
* send the statement to the database "preparation"-process
* check if the database had any troubles by asking it for errors
*/
$booking_sql = "INSERT INTO bookings (booking_name, booking_number, booking_phone, booking_email, booking_date) VALUES (?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($dbconn ,$booking_sql);
if(mysqli_errno($dbconn) !== 0){
trigger_error(mysqli_error($dbconn));
}
/*
* bind your variables to the prepared statement
* execute the statement
* again, ask if the database had any troubles
*/
mysqli_stmt_bind_param($stmt, "sssss", $name, $number, $phone, $email, $date);
mysqli_stmt_execute($stmt);
if(mysqli_errno($dbconn) !== 0){
trigger_error(mysqli_error($dbconn));
}
$_SESSION = array();
?>
<h2>Booking complete </h2>
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 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
I have an application where a user can send request edit to the admin, now the problem is how to store the id of the requested asset from user_asset table to the request table so I can display it to the admin's page with full details of the asset
when the user clicks on the request edit he gets a form with editable fields filled with current information but how can I store this asset's id so I can fetch it to the admin's table with information from both tables (user_assets, requests)
I have user_asset table
asset_id
asset_category
code
title
userid
and requests table
id
reason
assetid
user_id
this is what I have done so far
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
?>
and this is my form
<form method="post" action="req_ade.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
these are the errors I'm getting
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Incorrect integer value: '' for column 'assetid' at row 1' in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
( ! ) mysqli_sql_exception: Incorrect integer value: '' for column 'assetid' at row 1 in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
There is no "id" in your $_GET array. So your $asset_id variable will be empty and a empty string is not a valid int number. You should add (int) in your query:
mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". (int)$asset_id ."','" .$_SESSION['user_id'] . "')")
Or better check the the $_GET array before you use it. Like this:
If(isset($_GET['id']))
{
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
}
else
{
...
}
Thank you for all your suggestions.
After trying a lot of suggestions and manipulating with the code I have found a solution for it.
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_POST['asset_id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests1`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
and this is the form I have posted the asset_id in a hidden type
<form method="post" action="req_ade1.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="hidden" value="<?php echo $project['asset_id'];?>" name="asset_id" />
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
I Have a profile page and admin can edit profile users,
all process on one page done,How i can refresh and update value form data after success query update ?
User.class file :
class User {
...
public function updateUser($id, $firstname, $lastname, $phone, $birthday, $managerid)
{
$con = $this->DBconnect();
$id = (int)$id;
$managerid = $this->checkParam($managerid);
$firstname = $firstname;
$lastname = $lastname;;
$mobile = $phone;
$birthday = $this->checkParam($birthday);
$query = "UPDATE `users` SET `manager_id` = :manager_id,`firstname` = :firstname,`lastname` = :lastname,`birthday` = :birthday,`mobile` = :mobile WHERE `id` = :id";
$result = $con->prepare($query);
$result->BindParam(':id', $id, PDO::PARAM_INT);
$result->BindParam(':manager_id', $managerid, PDO::PARAM_INT);
$result->BindParam(':firstname', $firstname);
$result->BindParam(':lastname', $lastname);
$result->BindParam(':birthday', $birthday);
$result->BindParam(':mobile', $mobile);
$check = $result->execute();
return true;
}}
profile.php file :
<?php
if (isset($_GET['id'])) {
$id = (int)$_GET['id'];
}
$user = new User();
$user_info = $user->getuser($id);
while ($info = $user_info->fetch(PDO::FETCH_ASSOC)) {
$firstname = $info['firstname'];
$lastname = $info['lastname'];
$mobile = $info['mobile'];
$birthday = $info['birthday'];
$managerid = $info['manager_id'];
}
$manager_ob = new Manager();
$managers = $manager_ob->getAllManager();
$managers_name = array();
while ($manager = $managers->fetch(PDO::FETCH_ASSOC)) {
$managers_list[] = $manager;
}
if (isset($_POST['edit-profile'])) {
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
}
?>
<form method="post" action="#" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">ID</label>
<div class="col-sm-10"><input type="text" readonly class="form-control" name="user_id" id="user_id" value="<?php echo check_param($id); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_firstname" value="<?php echo check_param($firstname); ?>" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_lastname" value="<?php echo check_param($lastname); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_mobile" value="<?php echo check_param($mobile); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label" for="birthday">Birthday
</label>
<div class="col-sm-10"><input id="birthday" type="text" class="form-control" name="user_birthday"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Manager</label>
<div class="col-sm-10"><select class="form-control m-b" name="manager_id">
<?php foreach ($managers_list as $managers_n) { ?>
<option <?php if ($managers_n['id'] == $managerid) {
echo 'selected';
} ?>
value="<?php echo $managers_n['id']; ?>"> <?php echo $managers_n['name']; ?></option>;
<?php }
?>
</select>
</div>
</div>
<input type="submit" name="edit-profile" class="btn btn-block btn-w-m btn-success"
value="Edit profile">
</form>
i load profile data after submit edit :
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
only display message Profile Edited but must be refresh page for renew data
I must fetch again query for update values? or have better way ?
I suggest you use Ajax for this this is probably the best way to change the data without refreshing. More info about (jQuery) ajax http://api.jquery.com/jquery.ajax/
Your other option is to force a refresh after the submit. You can do this in PHP like so:
Header('Location: '.$_SERVER['PHP_SELF']);
I would suggest choosing ajax to tackle this problem though.
Good luck :)
It's a simple code but i can't understand where is my mistake. I want to display succesfull message under the form when i click the submit but the message stays there all the time. When i enter in the page where the form is the message is under the form. How to take it out only when the query is succesfull ?
<?php
$posted = false;
if(isset($_POST['add']))
{
$posted = true;
$email = $_POST['email'];
$name = $_POST['name'];
$rate = $_POST['rate'];
$comment = $_POST['comment'];
$dth = date("Y-m-d H:i:s");
$q = "INSERT INTO reviews(email, name, rate, comment, date_created) VALUES ('$email', '$name', '$rate', '$comment', '$dth')";
$k = mysqli_query($con,$q);
}
?>
<body>
<h1>Leave a review</h1>
<div class="error-conteiner">
</div>
<div class="clear"></div>
<form action="" method="post" class="form-content">
<div class="left">
<div class="field">
<label>E-mail <span class="required">*</span></label>
<input type="text" value="" name="email" class="required-field" data-validate="email"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Name</label>
<input type="text" value="" name="name"/>
</div>
<div class="clear"></div>
<div class="field">
<label>Rate</label>
<select name="rate">
<option value=''>Choose rate</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
</div>
<div class="left">
<label>Comment <span class="required">*</span></label>
<textarea name="comment" class="comment required-field"></textarea>
</div>
<input type="submit" value="Send" class="btn" name="add" />
</form>
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
</body>
</html>
Maybe it is not professional and nice solution, but works well, if you make a query after the post with ex. $email and $name or other parameters. If the result is not empty, then you can put the results or just a simple message also into the output.
Replace
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with
<?php
if($posted===true){
if($k) echo "Thank you for your comment!";
else die(mysqli_error());
}
?>
Maybe you have to put {} after your first if
Directly below:
$k = mysqli_query($con,$q);
add:
if(!$k) {
die(mysqli_error());
}
If the query wasn't executed, for whatever reason, show the error and stop.
You might consider adding a development mode variable or constant, because the mysqli_error() message is only valuable for the developer and the content is not for your users eyes. Anyway:
Replace:
<?php
if($posted){
if($k)
echo "Thank you for your comment!";
else
die(mysqli_error());
}
?>
with:
if($posted === true) {
echo 'Thank you for your comment!';
}
The mysql error is handled, where it occurs.
The success message is only displayed, when successfully send.
It's also possible to make a header redirection on success. But that depends, on what you like.
if($posted === true) {
header('Location: success-message-page.php');
exit;
}