Php form with non required file upload - php

I'm trying to fix this form in order to make the file upload an option rather than required since I won't always have images available. So far this is what I came up with from my research around, but I still get a message saying file is required.
else if (isset($_POST['add_news_btn'])) {
include 'connect.php';
$newsdate = (isset($_POST['newsdate']) ? $_POST['newsdate'] : null);
$newstitle = (isset($_POST['newstitle']) ? $_POST['newstitle'] : null);
$newscatagory = (isset($_POST['newscategory']) ? $_POST['newscategory'] : null);
$newstext = (isset($_POST['newstext']) ? $_POST['newstext'] : null);
// upload file
if (!empty($_FILES['newsuploader'])) {
if(move_uploaded_file($_FILES["newsuploader"]["tmp_name"], "../media/images/" .$_FILES["newsuploader"]["name"]))
echo "Saved";
$imageURL = "media/images/" .$_FILES["newsuploader"]["name"];
/* else
$imageURL='';
*/
if (isset($_POST['display']) && $_POST['display'] == '1')
{
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory, imageURL, display_image) VALUES(?, ?, ?, ?, ?, 1)");
}
else {
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory, imageURL, display_image) VALUES(?, ?, ?, ?, ?, 0)");
}
} else if (empty($_FILES['newsuploader'])){
$imageURL = "media/images/news-logo.png";
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory, imageURL, display_image) VALUES(?, ?, ?, ?, ?, 0)");
}
$stmt->bind_param('sssss', $newsdate, $newstitle, $newstext, $newscatagory, $imageURL);
$stmt->execute();
$stmt->close();
echo "done";
}
}
Corresponding Form
<form name="news-page" action="" method="POST" enctype="multipart/form-data">
<h1>News</h1>
<span id="newstitle">
<p id="newstitle">News Title</p>
<input id="title" type="text" name="newstitle" value="News Title"/>
</span>
<span id="newsdate">
<p>News Date</p>
<input id="news_date" type="text" name="newsdate" value="News Date"/>
</span>
<span id="category">
<p>News Category</p>
<input id="newscategory" type="text" name="newscategory" value="News Category"/>
</span>
<p id="news_info">News Information</p>
<textarea id="newsinfo" name="newstext">Bacon ipsum dolor amet turducken boudin sirloin ..</textarea>
<div id="newsimage">
<img src/>
<p>Insert News Image</p>
<label class="myLabel" id="news-image-upload">
<input type="file" required name="newsuploader" id="fileToUpload" />
<span>Select Image</span>
</label>
<input type="checkbox" name="display" value="1">Display Image
<button type="submit" name="add_news_btn">Add News</button>
</div>
</form>

Remove the "required" attribue from the input element (in the form).
Replace:
<input type="file" required name="newsuploader" id="fileToUpload" />
With:
<input type="file" name="newsuploader" id="fileToUpload" />

Related

HTML form not submitting to PHP

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

Bind_param warning number of variables and parameters don't match [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I go to edit anything other than the image and link I get this error "", although it still updates the item and displays it in my list of products as the new updated info. The parameters and variables match and i have counted a number of times, I am starting to think its something else in the code.
enter image description here
enter image description here
Here is my code for my edit page:
<?php
require_once 'connect.php';
require_once 'header.php';
?>
<!DOCTYPE html>
<html>
<head>
<script src="//cdn.ckeditor.com/4.5.5/standard/ckeditor.js"></script>
</head>
<body>
<div class="container">
<?php
if(isset($_POST['update'])){
if( empty($_POST['category']) || empty($_FILES['image']) || empty($_POST['productname']) || empty($_POST['price']) || empty($_POST['description']) || empty($_POST['details']) || empty($_POST['spec_1']) || empty($_POST['spec_2']) || empty($_POST['spec_3'])|| empty($_POST['spec_4']) || empty($_POST['spec_5']) || empty($_POST['spec_6']) || empty($_POST['spec_7']) || empty($_POST['spec_8']) || empty($_POST['spec_9']) || empty($_POST['spec_10']) || empty($_POST['info_1']) || empty($_POST['info_2']) || empty($_POST['info_3'])|| empty($_POST['info_4']) || empty($_POST['info_5']) || empty($_POST['info_6']) || empty($_POST['info_7']) || empty($_POST['info_8']) || empty($_POST['info_9']) || empty($_POST['info_10']) || empty($_FILES['link_1']) )
{
echo "Please fillout all required fields"; }
$category = $_POST['category'];
$image = $_FILES['image']['name'];
$productname = $_POST['productname'];
$price = $_POST['price'];
$description = $_POST['description'];
$details = $_POST['details'];
$spec_1 = $_POST['spec_1'];
$spec_2 = $_POST['spec_2'];
$spec_3 = $_POST['spec_3'];
$spec_4 = $_POST['spec_4'];
$spec_5 = $_POST['spec_5'];
$spec_6 = $_POST['spec_6'];
$spec_7 = $_POST['spec_7'];
$spec_8 = $_POST['spec_8'];
$spec_9 = $_POST['spec_9'];
$spec_10 = $_POST['spec_10'];
$info_1 = $_POST['info_1'];
$info_2 = $_POST['info_2'];
$info_3 = $_POST['info_3'];
$info_4 = $_POST['info_4'];
$info_5 = $_POST['info_5'];
$info_6 = $_POST['info_6'];
$info_7 = $_POST['info_7'];
$info_8 = $_POST['info_8'];
$info_9 = $_POST['info_9'];
$info_10 = $_POST['info_10'];
$link_1 = $_FILES['link_1']['name'];
if ((!($_FILES['image']['name'])) && (!($_FILES['link_1']['name'])) ) {
$sql = $con->prepare("UPDATE products SET category = ?, productname = ?, price = ?, description = ?, details = ?, spec_1 = ?, spec_2 = ?,
spec_3 = ?, spec_4 = ?, spec_5 = ?, spec_6 = ?, spec_7 = ?, spec_8 = ?, spec_9 = ?, spec_10 = ?, info_1 = ?, info_2 = ?,
info_3 = ?, info_4 = ?, info_5 = ?, info_6 = ?, info_7 = ?, info_8 = ?, info_9 = ?, info_10 = ? WHERE product_id = ?");
$sql->bind_param("sssssssssssssssssssssssssi",$category, $productname, $price, $description, $details, $spec_1, $spec_2, $spec_3, $spec_4, $spec_5, $spec_6, $spec_7, $spec_8, $spec_9, $spec_10, $info_1, $info_2, $info_3, $info_4, $info_5, $info_6, $info_7,$info_8,$info_9,$info_10, $_GET["id"]);
$sql->execute();
}else
$sql = $con->prepare("UPDATE products SET category = ?, image = ?, productname = ?, price = ?, description = ?, details = ?, spec_1 = ?, spec_2 = ?,
spec_3 = ?, spec_4 = ?, spec_5 = ?, spec_6 = ?, spec_7 = ?, spec_8 = ?, spec_9 = ?, spec_10 = ?, info_1 = ?, info_2 = ?,
info_3 = ?, info_4 = ?, info_5 = ?, info_6 = ?, info_7 = ?, info_8 = ?, info_9 = ?, info_10 = ?, link_1 = ? WHERE product_id = ?");
$sql->bind_param("sssssssssssssssssssssssssssi", $category, $image, $productname, $price, $description, $details, $spec_1, $spec_2, $spec_3, $spec_4, $spec_5, $spec_6, $spec_7, $spec_8, $spec_9, $spec_10, $info_1, $info_2, $info_3, $info_4, $info_5, $info_6, $info_7,$info_8,$info_9,$info_10, $link_1, $_GET["id"]);
if($sql->execute()) {
echo "<div class='alert alert-success'>Successfully updated product</div>";
}else{
echo "<div class='alert alert-danger'>Error: There was an error while updating product info</div>";
}
}
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$sql = $con->prepare("SELECT * FROM products WHERE product_id = ?");
$sql->bind_param('i', $id);
$sql->execute();
$result = $sql->get_result();
if($result->num_rows < 1){
header('Location: index.php');
exit;
}
$row = $result->fetch_assoc();
?>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="box2">
<h3><i class="glyphicon glyphicon-plus"></i> Modify Product</h3>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $row['product_id']; ?>" name="productid">
<label for="category">Category</label>
<input type="text" id="category" name="category" value="<?php echo $row['category']; ?>" class="form-control"><br>
<label for="name">Image</label><br><br>
<span><?php echo '<img src="Images/'. $row['image'], '" />'?></span><br><br>
<input type="file" name="image" id="image" value="<?php echo $row['image']; ?>" class="form-control"><br>
<label for="name">Name</label>
<input type="text" name="productname" id="name" value="<?php echo $row['productname']; ?>" class="form-control"><br>
<label for="price">Price</label>
<input type="text" name="price" id="price" value="<?php echo $row['price']; ?>" class="form-control"><br>
<label for="description">Description</label>
<input type="text" name="description" id="description" value="<?php echo $row['description']; ?>" class="form-control"><br>
<h3><i class="glyphicon glyphicon-plus"></i> Modify Product Details</h3><br>
<label class="heading" for="heading">Product Details</label><br>
<textarea name="details" id="details" class="form-control ckeditor">
<?php echo $row['details']; ?>
</textarea>
<br>
<h3><i class="glyphicon glyphicon-plus"></i> Modify Specifications</h3><br>
<label class="heading" for="heading">Heading</label>
<input type="text" id="spec_1" name="spec_1" value="<?php echo $row['spec_1']; ?>"class="form-control head_1"><br>
<label class="information" for="information">Information</label>
<input type="text" id="info_1" name="info_1" value="<?php echo $row['info_1']; ?>" class="form-control info_1"><br>
<input type="text" id="spec_2" name="spec_2" value="<?php echo $row['spec_2']; ?>"class="form-control head_2"><br>
<input type="text" id="info_2" name="info_2" value="<?php echo $row['info_2']; ?>" class="form-control info_2"><br>
<input type="text" id="spec_3" name="spec_3" value="<?php echo $row['spec_3']; ?>"class="form-control head_3"><br>
<input type="text" id="info_3" name="info_3" value="<?php echo $row['info_3']; ?>" class="form-control info_3"><br>
<input type="text" id="spec_4" name="spec_4" value="<?php echo $row['spec_4']; ?>"class="form-control head_4"><br>
<input type="text" id="info_4" name="info_4" value="<?php echo $row['info_4']; ?>" class="form-control info_4"><br>
<input type="text" id="spec_5" name="spec_5" value="<?php echo $row['spec_5']; ?>"class="form-control head_5"><br>
<input type="text" id="info_5" name="info_5" value="<?php echo $row['info_5']; ?>" class="form-control info_5"><br>
<input type="text" id="spec_6" name="spec_6" value="<?php echo $row['spec_6']; ?>"class="form-control head_6"><br>
<input type="text" id="info_6" name="info_6" value="<?php echo $row['info_6']; ?>" class="form-control info_6"><br>
<input type="text" id="spec_7" name="spec_7" value="<?php echo $row['spec_7']; ?>"class="form-control head_7"><br>
<input type="text" id="info_7" name="info_7" value="<?php echo $row['info_7']; ?>" class="form-control info_7"><br>
<input type="text" id="spec_8" name="spec_8" value="<?php echo $row['spec_8']; ?>"class="form-control head_8"><br>
<input type="text" id="info_8" name="info_8" value="<?php echo $row['info_8']; ?>" class="form-control info_8"><br>
<input type="text" id="spec_9" name="spec_9" value="<?php echo $row['spec_9']; ?>"class="form-control head_9"><br>
<input type="text" id="info_9" name="info_9" value="<?php echo $row['info_9']; ?>" class="form-control info_9"><br>
<input type="text" id="spec_10" name="spec_10" value="<?php echo $row['spec_10']; ?>"class="form-control head_10"><br>
<input type="text" id="info_10" name="info_10" value="<?php echo $row['info_10']; ?>" class="form-control info_10"><br>
<h3 class="links"><i class="glyphicon glyphicon-plus"></i> Add New Links</h3><br>
<label class="links" for="links">Links</label><br><br>
<span><?php echo $row['link_1']?></span>
<input type="file" name="link_1" id="link_1" value="<?php echo $row['link_1']; ?>" class="form-control"><br>
<br>
<br>
<br>
<input type="submit" name="update" class="btn btn-success button2" value="Update">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Your help would be greatly appreciated and apologies I am still new and first attempt at a crud system.
Thank you.
The problem is you didn't open { at else line 61 so:
}else
$sql = $con->prepare
to:
}else{
$sql = $con->prepare

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens - help needed

I've tried making a website which has a database connected to it and I'm getting the error message below
INSERT INTO Diák (oktatási_id, vezeték_név, kereszt_név, évfolyam, születési_dátum, város, utca, házszám, irányítószám, szak, kar)
values (:oktatási_id, :vezeték_név, :kereszt_név, :évfolyam, :születési_dátum, :város, :utca, :házszám, :irányítószám, :szak, :kar)
SQLSTATE[HY093]: Invalid parameter number: number of bound variables
does not match number of tokens
This is my PHP code that I have written below
<?php
require "../config.php";
require "../common.php";
if (isset($_POST['submit'])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$new_user = array(
"oktatási_id" => $_POST['oktatási_id'],
"vezeték_név" => $_POST['vezeték_név'],
"kereszt_név" => $_POST['kereszt_név'],
"évfolyam" => $_POST['évfolyam'],
"születési_dátum" => $_POST['születési_dátum'],
"város" => $_POST['város'],
"utca" => $_POST['utca'],
"házszám" => $_POST['házszám'],
"irányítószám" => $_POST['irányítószám'],
"szak" => $_POST['szak'],
"kar" => $_POST['kar'],
);
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"Diák",
implode(", ", array_keys($new_user)),
":" . implode(", :", array_keys($new_user))
);
$statement = $connection->prepare($sql);
$statement->execute($new_user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['kereszt_név']); ?> adatát sikeresen hozzá adtuk az adatbázishoz.</blockquote>
<?php endif; ?>
<h2>Felhasználó hozzáadása az adatbázishoz</h2>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<label for="oktatási_id">oktatási_id</label>
<input type="text" name="oktatási_id" id="oktatási_id">
<label for="vezeték_név">Vezeték Név</label>
<input type="text" name="vezeték_név" id="vezeték_név">
<label for="kereszt_név">Kereszt Név</label>
<input type="text" name="kereszt_név" id="kereszt_név">
<label for="évfolyam">évfolyam</label>
<input type="text" name="évfolyam" id="évfolyam">
<label for="születési_dátum">Születési dátum</label>
<input type="date" name="születési_dátum" id="születési_dátum">
<label for="város">város</label>
<input type="text" name="város" id="város">
<label for="utca">utca</label>
<input type="text" name="utca" id="utca">
<label for="házszám">házszám</label>
<input type="text" name="házszám" id="házszám">
<label for="irányítószám">irányítószám</label>
<input type="text" name="irányítószám" id="irányítószám">
<label for="kar">kar</label>
<input type="text" name="kar" id="kar">
<label for="szak">szak</label>
<input type="text" name="szak" id="szak">
<input type="submit" name="submit" value="Submit">
</form>
Vissza a kezdő oldalra
<?php require "templates/footer.php"; ?>
It took me a while to find, but I believe that PDO::prepare passes the named parameters through a regular expression [:][a-zA-Z0-9_]+. https://github.com/php/php-src/blob/master/ext/pdo/pdo_sql_parser.re#L48. Your diacritic characters are being clobbered.
The only alternative that I know about it to use unnamed placeholders instead - ?. Something like:
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"Diak",
implode(", ", array_keys($new_user)),
implode(', ', array_fill(0, sizeof($new_user), '?'))
);
Which will produce:
INSERT INTO Diák (oktatási_id, vezeték_név, kereszt_név, évfolyam, születési_dátum, város, utca, házszám, irányítószám, szak, kar) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
You'll then have to change your execute method as follows:
$statement->execute(array_values($new_user));

Word 'Variable' appears in the URL and not the number ID - PHP

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-->

php form with text inputs and image uploader

Hi all I'm looking for some guidance as to how can I build a php form which includes both text and an image uploader. I am able to do the two forms separately but am having a bit of difficulty in joining things together.
My html form:
<form name="news-page" action="" method="POST" enctype="multipart/form-data">
<h1>News</h1>
<span id="newstitle">
<p id="newstitle">News Title</p>
<input id="title" type="text" name="newstitle" value="News Title"/>
</span>
<span id="newsdate">
<p>News Date</p>
<input id="news_date" type="text" name="newsdate" value="News Date"/>
</span>
<span id="category">
<p>News Category</p>
<input id="newscategory" type="text" name="newscategory" value="News Category"/>
</span>
<p id="news_info">News Information</p>
<textarea id="newsinfo" name="newstext">Bacon ipsum dolor amet turducken boudin sirloin ..</textarea>
<div id="newsimage">
<img src/>
<p>Insert News Image</p>
<label class="myLabel" id="news-image-upload">
<input type="file" required name="newsuploader" id="fileToUpload" />
<span>Select Image</span>
</label>
<button type="submit" name="add_news_btn">Add News</button>
</div>
</form>
Code to insert text
if (isset($_POST['add_news_btn'])) {
$newsdate = (isset($_POST['newsdate']) ? $_POST['newsdate'] : null);
$newstitle = (isset($_POST['newstitle']) ? $_POST['newstitle'] : null);
$newscatagory = (isset($_POST['newscategory']) ? $_POST['newscategory'] : null);
$newstext = (isset($_POST['newstext']) ? $_POST['newstext'] : null);
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory) VALUES(?, ?, ?, ?)");
$stmt->bind_param('ssss', $newsdate, $newstitle, $newstext, $newscatagory);
$stmt->execute();
$stmt->close();
echo "done";
}
code to upload image
if (isset($_FILES['newsuploader'])) {
if ($_FILES["newsuploader"]["error"] > 0) {
echo "No file chosen</br>";
echo "Database fail</br>";
}
else {
move_uploaded_file($_FILES["newsuploader"]["tmp_name"], "../media/images/" . $_FILES["newsuploader"]["name"]);
echo "Saved";
$file = "media/images/" . $_FILES["newsuploader"]["name"];
include 'connect.php';
if (!mysqli_select_db($conn, "mostacms_db")) {
echo "Error: " . mysql_error();
}
else echo "all good";
}
$stmt = $conn->prepare("INSERT INTO news(imageURL) VALUES(?)");
$stmt->bind_param('s', $file);
$stmt->execute();
$conn->close();
}
Try posting into this php file.
if (isset($_POST['add_news_btn'])) {
include 'connect.php';
$newsdate = (isset($_POST['newsdate']) ? $_POST['newsdate'] : null);
$newstitle = (isset($_POST['newstitle']) ? $_POST['newstitle'] : null);
$newscatagory = (isset($_POST['newscategory']) ? $_POST['newscategory'] : null);
$newstext = (isset($_POST['newstext']) ? $_POST['newstext'] : null);
// upload file
if (isset($_FILES['newsuploader'])) {
if(move_uploaded_file($_FILES["newsuploader"]["tmp_name"], "../media/images/" . $_FILES["newsuploader"]["name"]))
echo "Saved";
$imageURL = "media/images/" . $_FILES["newsuploader"]["name"];
}
else
$imageURL='';
// update details to DB
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory,imageURL ) VALUES(?, ?, ?, ?,?)");
$stmt->bind_param('sssss', $newsdate, $newstitle, $newstext, $newscatagory, $imageURL);
$stmt->execute();
$stmt->close();
}
Note: To avoid duplicate file insertion try changing the filename to something unique before saving it.
try to change this statement
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory) VALUES(?, ?, ?, ?)");
$stmt->bind_param('ssss', $newsdate, $newstitle, $newstext, $newscatagory);
to
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory) VALUES(?, ?, ?, ?,?)");
$stmt->bind_param('sssss', $newsdate, $newstitle, $newstext, $newscatagory,$file);

Categories