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);
Related
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 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-->
This is a project for school. I'm am trying to post to the database, but after I click on submit it comes back with an error about the line with bind_param:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in /var/www/html/ticketsysteem/acties/nieuwTicket.php:42 Stack trace: #0 {main} thrown in /var/www/html/ticketsysteem/acties/nieuwTicket.php on line 42
Can somebody help me?
<?php
//var
$naam = trim($_POST["klantNaam"]);
$achternaam = trim($_POST["klantAchternaam"]);
$tel = trim($_POST["klantTel"]);
$adres = trim($_POST["klantAdres"]);
$postcode = trim($_POST["klantPostc"]);
$stad = trim($_POST["klantStad"]);
$email = trim($_POST["klantEmail"]);
//nieuwe klant
if (isset($_POST['submit1'])) {
$insertklant= $connectie->prepare("INSERT INTO klant klantAchternaam = $achternaam,
klantNaam = $naam, klantTel = $tel, klantAdres = $adres, klantPostc = $postcode,
klantStad = $stad, klantEmail = $email");
$insertklant->bind_param('sssssss', $achternaam, $naam, $tel, $adres, $postcode, $stad, $email);
if($insertklant->execute()) {
echo 'gelukt!';
}
}
?>
<form name="nieuwTicket" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<button onclick="nieuwek()" type="button" id="nk" >nieuwe klant </button>
<label class="hidden01">naam:</label><input id="text1" type="text" name="klantNaam" class="hidden"/><br>
<label class="hidden01">achternaam:</label><input id="text1" type="text" name="klantAchternaam" class="hidden"/><br>
<label class="hidden01">adres:</label><input id="text1" type="text" name="klantAdres" class="hidden"/><br>
<label class="hidden01">postcode:</label><input id="text1" type="text" name="klantPostc" class="hidden"/><br>
<label class="hidden01">woonplaats:</label><input id="text1" type="text" name="klantStad" class="hidden"/><br>
<label class="hidden01">telefoonnummer:</label><input id="text1" type="text" name="klantTel" class="hidden"/><br>
<input type="submit" name="submit1" value="invoeren" class="hidden">
</form>
Learn how to use prepared statements and what they actually do:
<?php
$stmt = $connectie->prepare("
INSERT INTO klant
klantAchternaam = ?,
klantNaam = ?,
klantTel = ?,
klantAdres = ?,
klantPostc = ?,
klantStad = ?,
klantEmail = ?
");
if($stmt){
$stmt->bind_param('sssssss', $achternaam, $naam, $tel, $adres, $postcode, $stad, $email);
if($stmt->execute()) {
echo 'gelukt!';
}
}
?>
Your current code is wide open to sql injection, while the above code is fully secured against them. The whole idea of prepared statements is that you never have to concat user submitted values directly to the sql query.
I have a csv upload script that works perfectly on my PC and other PC's have been tested as well. I have a client who is trying this script on their Mac and it returns an error: Error no file selected.
The permissions on the upload folder are 755.
Really need to find out the cause of this. You can see my script and form below.
define("UPLOAD_DIR", "/home/path/public_html/uploads/".$company."/");
$message = null;
$allowed_extensions = array('csv');
if(!empty($_FILES['file'])){
if($_FILES['file']['error'] === 0){
$file = explode(".", $_FILES['file']['name']);
$extension = array_pop($file);
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $_FILES['file']["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
if(in_array($extension, $allowed_extensions)){
if(move_uploaded_file($_FILES['file']['tmp_name'],
UPLOAD_DIR . $name)){
if(($handle = fopen(UPLOAD_DIR . $name, "r")) !== false){
$keys = array();
$out = array();
$line =1;
while(($row = fgetcsv($handle, 0, ',', '"')) !== false){
foreach($row as $key => $value){
if($line === 1){
$keys[$key] = $value;
}else{
$out[$line][$key] = $value;
}
}
$line++;
}
fclose($handle);
if(!empty($keys) && !empty($out)){
foreach($out as $key => $value){
$sql = "INSERT INTO ".$company."(id,prefix,fullname,last_name,business,address1,address2,address3,town,county,postcode,email,website,telephone1,telephone2,telephone3,landing_page,assigned_to,question1,question2,question3,question4,question5,question6,date,status,leadtype,file,gclid,leadid,tostep,ip,client_xp)VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$date = date("Y-m-d H:i:s");
$status = "New Lead";
$client_xp = 1;
$statement = $db->prepare($sql);
$statement->bindParam(1, $value[0], PDO::PARAM_STR);
$statement->bindParam(2, $value[1], PDO::PARAM_STR);
$statement->bindParam(3, $value[2], PDO::PARAM_STR);
$statement->bindParam(4, $value[3], PDO::PARAM_STR);
$statement->bindParam(5, $value[4], PDO::PARAM_STR);
$statement->bindParam(6, $value[5], PDO::PARAM_STR);
$statement->bindParam(7, $value[6], PDO::PARAM_STR);
$statement->bindParam(8, $value[7], PDO::PARAM_STR);
$statement->bindParam(9, $value[8], PDO::PARAM_STR);
$statement->bindParam(10, $value[9], PDO::PARAM_STR);
$statement->bindParam(11, $value[10], PDO::PARAM_STR);
$statement->bindParam(12, $value[11], PDO::PARAM_STR);
$statement->bindParam(13, $value[12], PDO::PARAM_STR);
$statement->bindParam(14, $value[13], PDO::PARAM_STR);
$statement->bindParam(15, $value[14], PDO::PARAM_STR);
$statement->bindParam(16, $value[15], PDO::PARAM_STR);
$statement->bindParam(17, $value[16], PDO::PARAM_STR);
$statement->bindParam(18, $value[17], PDO::PARAM_STR);
$statement->bindParam(19, $value[18], PDO::PARAM_STR);
$statement->bindParam(20, $value[19], PDO::PARAM_STR);
$statement->bindParam(21, $value[20], PDO::PARAM_STR);
$statement->bindParam(22, $value[21], PDO::PARAM_STR);
$statement->bindParam(23, $value[22], PDO::PARAM_STR);
$statement->bindParam(24, $value[23], PDO::PARAM_STR);
$statement->bindParam(25, $date, PDO::PARAM_STR);
$statement->bindParam(26, $status, PDO::PARAM_STR);
$statement->bindParam(27, $value[26], PDO::PARAM_STR);
$statement->bindParam(28, $value[27], PDO::PARAM_STR);
$statement->bindParam(29, $value[28], PDO::PARAM_STR);
$statement->bindParam(30, $value[29], PDO::PARAM_STR);
$statement->bindParam(31, $value[30], PDO::PARAM_STR);
$statement->bindParam(32, $value[31], PDO::PARAM_STR);
$statement->bindParam(33, $client_xp, PDO::PARAM_STR);
$statement->execute();
}
$message = '
<div class="row">
<div class="col-lg-6">
<div class="alert alert-success">
Success. Import complete. <i class="fa fa-times pull-right"></i>
</div>
</div>
</div>';
}
}
}
} else {
$message = '
<div class="row">
<div class="col-lg-6">
<div class="alert alert-warning">
Only CSV\'s allowed <i class="fa fa-times pull-right"></i>
</div>
</div>
</div>';
}
} else {
$message = '
<div class="row">
<div class="col-lg-6">
<div class="alert alert-warning">
There was a problem with your upload. Please try again. <i class="fa fa-times pull-right"></i>
</div>
</div>
</div>';
}
}
<form enctype="multipart/form-data" method="POST" action="/import/">
<div class="form-body pal">
<div class="row">
<div class="col-md-12">
<div class="form-group">
CSV file to import:<br /><br /><input type="file" name="file" id="file">
</div>
</div>
</div>
<input type="submit" name="submit" class="btn btn-blue" value="Upload">
</div>
</form>
Ok so this ended up being a really simple solution by changing the first line of code to this
define("UPLOAD_DIR", "/home/path/public_html/uploads/$company/");
The inverted commas were closing the string before the company variable could be used, making the upload path invalid.
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" />