I feel this should be straight forward but the data isnt going in to the table.
When I try to save the data the code executes and displays this message:
$statusMsg1 = "A problem occurred, please try again.";
Which leads me to think the problem must be with the SQL, but nothing is standing out to me to highlight what the issue is.
I changed the SQL so that insert raw text, but this produces the same message.
postCodes.php
<?php
// Form saubmission script
include_once 'submit.php';
/* Attempt MySQL server connection. */
$mysqli = new mysqli("127.0.0.1", "root", "root", "bookingpage");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// SQL query execution
$sql = "SELECT * FROM Postcodes";
?>
<!-- Status message -->
<?php if(!empty($statusMsg1)){ ?>
<p class="stmsg"><?php echo $statusMsg1; ?></p>
<?php } ?>
<!-- GENERAL TAB -->
<p style="color:RGB(0,70,135)">You can use the text editor below to display text on your home page</p>
<form action="" method="post">
<div class="form-group">
<label for="postcode1">Enter Postcode Area</label>
<input style="font-size:12px" name="postCodetext" id="postCodetext" class="form-control required" value="e.g CF11">
</div>
<div class="form-group">
<label for="deliveryCost">Delivery Charge</label>
<input style="font-size:12px" name="costtext" id="costtext" class="form-control required" value="e.g 5.00">
</div>
<button type="button" class="save-settings btn btn-primary btn-xs"
title="<?= lang('save') ?>">
<span class="glyphicon glyphicon-floppy-disk"></span>
<?= lang('save') ?>
</button>
<input type="submit" name="submitPostCode" value="Save Data">
</form>
submit.php
<?php
// Include the database configuration file
require_once 'dbConfig.php';
$editorContent = $statusMsg = '';
$postCodeString = $statusMsg1 = '';
// SAVE POSTCODE & DELIVERY COST
if(isset($_POST['submitPostCode'])){
// Get editor content
$postCodeString = $_POST['postCodetext'];
$costString = $_POST['costtext'];
// Check whether the editor content is empty
if(!empty($postCodeString)){
// Insert editor content in the database
$insert1 = $db->query("INSERT INTO PostCodes (postCode, Cost) VALUES ('".$postCodeString."', '".$costString."')");
// If database insertion is successful
if($insert1){
$statusMsg1 = "Succeddfully Saved.";
}else{
$statusMsg1 = "A problem occurred, please try again.";
}
}else{
$statusMsg1 = 'You cannot save a blank postcode or delivery charge';
}
}
Related
Let me explain my problem briefly.I have image names in MYSQL database.
I need to change the image name when user uploads a new image using file input field.Otherwise the image name in database remain same.But My problem is when user doesn't upload any images the image name becomes empty in database.
My HTML code for changing a image
<form method="post" action="edit_store_img.php?id=<?php echo (int)$store['id'] ?>" class="clearfix" enctype="multipart/form-data">
<div class="form-group">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a store image</label>
<input type="file" name="storepic" value="<?php echo $store['pic']; ?>"/>
</div>
</div>
<hr>
<br>
<h3>Change Map Image For Store <?php echo remove_junk($store['name']);?></h3>
<hr>
<!-- below code is for map image -->
<?php if($store['pic'] === '0'): ?>
<img class="img-avatar img-circle" src="uploads/mapimg/no_image.jpg" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php else: ?>
<img class="img-avatar img-circle" src="uploads/mapimg/<?php echo $store['map']; ?>" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php endif;
?>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a Store map location image</label>
<input type="file" name="mappic" value="<?php echo $store['map']; ?>"/>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="edit_store_img" class="add-btn">Update Store image</button>
</div>
</form>
This is my PHP file for getting ID for that particular image
<?php
$store = find_by_id('store',(int)$_GET['id']);
if(!$store)
{
$session->msg("d","Missing store id.");
redirect('store.php');
}
?>
This is my PHP code for Storing image name in database
<?php
if(isset($_POST['edit_store_img']))
{
if(empty($errors))
{
/*below queries is for image upload */
$msg = "";
$map = $_FILES["mappic"]["name"];
$tempname = $_FILES["mappic"]["tmp_name"];
$mapfolder = "uploads/mapimg/".$map;
// Now let's move the uploaded image into the mapfolder: image
if (move_uploaded_file($tempname, $mapfolder)) {
$msg = "map Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$message = "";
$pic = $_FILES["storepic"]["name"];
$tempname = $_FILES["storepic"]["tmp_name"];
$picfolder = "uploads/storeimg/".$pic;
// Now let's move the uploaded image into the folder image
if (move_uploaded_file($tempname, $picfolder)) {
$message = "Image uploaded successfully";
}else{
$message = "Failed to upload image";
}
$query = "UPDATE store SET";
$query .=" map ='{$map}', pic ='{$pic}'";
$query .=" WHERE id ='{$store['id']}'";
$result = $db->query($query);
if($result && $db->affected_rows() === 1){
$session->msg('s',"store updated ");
redirect('store.php', false);
} else {
$session->msg('d',' Sorry failed to updated!');
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
else
{
$session->msg("d", $errors);
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
?>
I Need to store image name when user doesn't upload image.I need to avoid the image name db field becomes empty.
Below quirky will somehow fix your problem; however, this is not the correct way I think;
$query .=" map = IF('{$map}' != '', '{$map}', map), pic = IF('{$pic}' != '', '{$pic}', pic)";
We are just asking the database to update with the exiting column value if the passed value is empty.
The correct way should be not to take it for granted that the user have uploaded a file; as you are doing with these below lines in your code;
$map = $_FILES["mappic"]["name"];
...
$pic = $_FILES["storepic"]["name"];
You should be actually using IF conditions to check if some viable value has been set for those _FILES variables so you know what to process for and what not, and prepare your SQL UPDATE statement accordingly.
I am updating my form values . Image is already uploaded and can see on the form. When i only update the text value the image is remove and it showing blank.means it does not remains the same when i update it just remove automatically i think not getting the path for current image value when i updating other values. kindly help me to sort out this problem
like if i have to update only name of the person i change the name and other fields remains same. When i click on update all values remains same and also update one which i update but problem is this photo is remove not remain same
<?php
$v_id = $_GET['v_id'];
include "config.php";
$sql = "SELECT * FROM my_veh_ven WHERE v_id='$v_id'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result)) {
?>
<!-- form start -->
<form role="form" method="POST" action="updateVehicle.php?v_id=<?= $row["v_id"] ?>" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group col-md-offset-0 col-md-4">
<label for="">25+ Days Rent in PKR</label>
<input type="text" class="form-control" name="v_25_plus_rent" value="<?=$row["v_25_plus_rent"]?>">
</div>
<div class="form-group col-md-offset-0 col-md-8">
<label >Change Vehicle Picture</label>
<input type="file" name="image" id="myFile" value="images/<?=$row["image"]?>" accept="image/*">
</div>
<div class="form-group col-md-offset-0 col-md-4" style="text-align: center;">
<label for="exampleInputFile" style="text-align: center;" >Current Vehicle Picture</label>
<?php echo'<Image src="images/'.$row["image"].'" style="width:325px;height:220px;"></Image>'; ?>
</div>
<div class=" ">
<div class=" with-border" style="text-align:center;">
<h4 class="box-title" style="text-align:center;"><b>Vendor Details</b></h4>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer skin-yellow">
<button type="submit" name="submit" class="btn btn-primary skin-yellow">Update</button>
</div>
</form>
<?php
}
} else {
echo "Sorry something wrong";
}
mysqli_close($conn);
?>
updating file
<?php
include "config.php";
if(isset($_POST['submit']))
{
$target = "images/".basename($_FILES['image']['name']);
$v_type = $_POST["v_type"];
$v_name = $_POST["v_name"];
$v_man = $_POST["v_man"];
$v_model = $_POST["v_model"];
$v_color = $_POST["v_color"];
$v_trans = $_POST["v_trans"];
$v_1_15_rent = $_POST["v_1_15_rent"];
$v_16_25_rent = $_POST["v_16_25_rent"];
$v_25_plus_rent = $_POST["v_25_plus_rent"];
$v_reg = $_POST["v_reg"];
$vendor_name = $_POST["vendor_name"];
$vendor_mobile = $_POST["vendor_mobile"];
$vendor_price = $_POST["vendor_price"];
$image = $_FILES["image"]["name"];
$v_id=$_GET["v_id"];
$sql = " UPDATE my_veh_ven SET v_type='$v_type', v_name='$v_name' ,v_man='$v_man' ,v_color='$v_color', v_trans='$v_trans', v_1_15_rent='$v_1_15_rent' , v_16_25_rent='$v_16_25_rent' ,v_25_plus_rent='$v_25_plus_rent' , image='$image' , v_reg='$v_reg' ,vendor_name='$vendor_name', vendor_mobile='$vendor_mobile' ,vendor_price='$vendor_price' WHERE v_id='$v_id' ";
if (mysqli_query($conn, $sql))
{
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$success = "✓ Successfully Updated";
}
}
else
{
$fail = "X Not Updated";
}
}
mysqli_close($conn);
?>
Simple Solution while adding put your image name in 1 hidden variable like below
$hiddenImage = $row["image"]
add this hidden variable in your form
<input type='hidden' name='hiddenImage' value='<?php echo $hiddenImage ?>'
and while submit check whether your file input type will contain any data or not. If data/image exist upload this image in folder and same name in db. if image not exist get that input variable save in database.
for e.g :
if (isset($_FILES["image"]["tmp_name"]) && $_FILES["image"]["tmp_name"] != "") {
// upload file and save image name in variable like $imagename
}else{
// if image not upload this code will execute
$imagename = $_POST['hiddenImage'];
}
Save this $imagename variable data in database
An <input type="file"/> has no value attribute usage. The image, once uploaded, is on your server and that's about it. You cannot set the value of the input to anything that would be meaningful.
What you certainly want is to display the uploaded picture instead of the input, and present the input if the user wants to change it.
EDIT: Now that we have your PHP code, we can see that you are overwriting the $image variable even if empty
$image = $_FILES["image"]["name"];
You have to verify if $_FILES["image"] exists, else image will be null or undefined. And then you will update the database with a bad value. I suggest you treat your upload differently than other data:
<?php
include "config.php";
if(isset($_POST['submit']))
{
$target = "images/".basename($_FILES['image']['name']);
$v_type = $_POST["v_type"];
$v_name = $_POST["v_name"];
$v_man = $_POST["v_man"];
$v_model = $_POST["v_model"];
$v_color = $_POST["v_color"];
$v_trans = $_POST["v_trans"];
$v_1_15_rent = $_POST["v_1_15_rent"];
$v_16_25_rent = $_POST["v_16_25_rent"];
$v_25_plus_rent = $_POST["v_25_plus_rent"];
$v_reg = $_POST["v_reg"];
$vendor_name = $_POST["vendor_name"];
$vendor_mobile = $_POST["vendor_mobile"];
$vendor_price = $_POST["vendor_price"];
$v_id=$_GET["v_id"];
$sql = " UPDATE my_veh_ven SET v_type='$v_type', v_name='$v_name' ,v_man='$v_man' ,v_color='$v_color', v_trans='$v_trans', v_1_15_rent='$v_1_15_rent' , v_16_25_rent='$v_16_25_rent' ,v_25_plus_rent='$v_25_plus_rent' , v_reg='$v_reg' ,vendor_name='$vendor_name', vendor_mobile='$vendor_mobile' ,vendor_price='$vendor_price' WHERE v_id='$v_id' ";
if (mysqli_query($conn, $sql))
{
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$image = $_FILES["image"]["name"];
$success = "✓ Successfully Updated";
$sql = "UPDATE my_veh_ven SET image='$image' WHERE v_id='$v_id' ";
mysqli_query($conn, $sql)
}
}
else
{
$fail = "X Not Updated";
}
}
mysqli_close($conn);
?>
There's a simple solution for your problem. Whenever a form submits, check if $_FILES is set/any file is provided or not. If any file/image is provided, then update your database according to it. If the $_FILES array is empty, that means your image/file is not uploaded, and hence you can update it accordingly.
Something like below:
<?php
if(isset($_POST['submit'])){
//check for files or updated variables
if(isset($_FILES)){
//image is provided, now update values accrodingly in your database
echo "image/file provided";
}else{
//image is not uploaded, update other values in database expect image/file
echo "image/file not provided";
}
}else{
?>
<html>
<head><title>My demo form</title></head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
<input type="text" name="data_one">
<input type="file" name="my_file" accept="image/*">
<input type="submit" value="submit">
</body>
</html>
<?php
}
?>
I want make protection on form, if user after using form want send another message in less than a minute he should get refuse. Other way every thing should pass.
For now I got something like this on view:
<!-- If Success form message send display this -->
<?php if (isset($_GET['msgSuccessSent']) == 1) { ?>
<h1 class="page-title text-center">Dziękujemy za wysłanie wiadomości</h1>
<div class="text-center">
Wyślij kolejną wiadomość
</div>
<?php } else { ?>
<?php if (isset($_GET['msgTimerError']) == 1) { ?>
<div id="errorMessage" class="alert alert-danger" role="alert">Przed wysłaniem kolejnej wiadomości musisz odczekać conajmniej minutę.</div>
<?php } ?>
<!-- If message isn't sent display form -->
<h1 class="page-title text-center">Formularz kontaktowy</h1>
<!-- Contact form -->
<form action="contact_send.php" method="post">
<!-- First name input -->
<div class="form-group">
<label for="firstName">Imię</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="Wpisz swoje imię">
</div>
<!-- Second name input -->
<div class="form-group">
<label for="secondName">Nazwisko</label>
<input type="text" class="form-control" id="secondName" name="secondName" placeholder="Wpisz swoje nazwisko">
</div>
<!-- Phone number input -->
<div class="form-group">
<label for="phoneNumber">Telefon kontaktowy</label>
<input type="tel" class="form-control" id="phoneNumber" name="phoneNumber" placeholder="Wpisz swój numer telefonu">
</div>
<!-- Email address input -->
<div class="form-group">
<label for="email">Adres e-mail</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Wpisz swój adres e-mail">
</div>
<!-- Message textarea -->
<div class="form-group">
<label for="message">Treść wiadomości</label>
<textarea type="text" class="form-control" id="message" name="message" rows="3"></textarea>
</div>
<!-- Send message button -->
<button type="reset" class="btn btn-default">Wyczyść formularz</button>
<button type="submit" class="btn btn-default pull-right">Wyślij</button>
</form>
<!-- Contact form end -->
<!-- End of If message isn't sent display form -->
<?php } ?>
And this is my contact_send.php file:
<?php
// Uncomment if you want to use session to check last form send
session_start();
$_SESSION['time'] = date('H:i:s');
header('Content-type: text/plain; charset=utf-8');
# Database connection settings
$dbHost = 'localhost'; // database hostname
$dbName = 'contactForm'; // database name
$dbUser = 'root'; // database user name
$dbPswd = ''; // database password
// Set connection
$connectionDb = new mysqli($dbHost, $dbUser, $dbPswd, $dbName);
// Check connection
if ($connectionDb->connect_error) {
die("Connection failed: " . $connectionDb->connect_error);
}
mysqli_set_charset( $connectionDb, 'utf8'); // change charset for mysqli to utf8
# Require ContactSend and DatabaseQuery class
require 'contact.class.php';
# Get ContactSend class
$sendEmail = new ContactSend();
$ipAddress = $_SERVER['REMOTE_ADDR']; // get user ip address
$currentDate = date('Y-m-d H:i:s'); // get Date time when user send form
# ***
# Here I check if time of last form send is greater than minute
# ***
$sqlCheck = "SELECT * FROM contactForm WHERE ipAddress = '$_SERVER[REMOTE_ADDR]' AND dateSend > DATE_SUB(NOW(),INTERVAL 1 MINUTE)";
if ($connectionDb->query($sqlCheck) === TRUE) {
$sendEmail->redirectToForm('form.php?msgTimerError=1');
} else {
// insert form values into database
$sqlQueryInsert =
"INSERT INTO contactForm (
firstName,
secondName,
phoneNumber,
email,
message,
dateSend,
ipAddress)
VALUES (
'$_POST[firstName]',
'$_POST[secondName]',
'$_POST[phoneNumber]',
'$_POST[email]',
'$_POST[message]',
'$currentDate',
'$ipAddress'
)";
// if data was save send mail and redirect to form
if ($connectionDb->query($sqlQueryInsert) === TRUE) {
# Get Parametrs from form
$sendEmail->sendTo = "kuchar.rafal#gmail.com"; // here insert your email address that you want get mails
$sendEmail->subject = "Tytuł wiadomości"; // here insert Subject of email
$sendEmail->firstName = $_POST['firstName']; // get user first name
$sendEmail->secondName = $_POST['secondName']; // get user second name
$sendEmail->phoneNumber = $_POST['phoneNumber']; // get user phone number
$sendEmail->email = $_POST['email']; // get user email address
// make mail content and insert form values into it
$sendEmail->message = "
Imię: " . $_POST['firstName'] . "
Nazwisko: " . $_POST['secondName'] . "
Numer telefonu: " . $_POST['phoneNumber'] . "
Adres email: " . $_POST['email'] . "
Wiadomość: " . $_POST['message'];
$sendEmail->mailSender(); // send mail
} else {
echo "Error: " . $sqlQueryInsert . "<br>" . $connectionDb->error; // display error if database connection or query has error
}
// close connection to database
$connectionDb->close();
// redirect to form
$sendEmail->redirectToForm('form.php?msgSuccessSent=1');
}
?>
$msgTimerError should display if in database exist row with user IP and date of create is less than minute other ways it should just display form.
$sqlCheck is for check in database if time of last form send is greater than minute if its not it redirect user to form.php with msgTimerError=1 with method get, otherwise it will add new form values to database and send mail.
Ok i changed line in contact_send.php so it works... (im so ashamed...)
# Check if user send form less than minute, if true return to form with error
$sqlCheck = "SELECT * FROM contactForm WHERE ipAddress = '$ipAddress' AND dateSend > DATE_SUB(NOW(),INTERVAL 1 MINUTE) LIMIT 1";
$result = $connectionDb->query($sqlCheck);
if (mysqli_fetch_row($result)) {
$sendEmail->redirectToForm('form.php?msgTimerError=1'); // return to form page
} else {
I am trying to upload 2 images and save the file name for each file to MySQL database. I have tried different options but I can't get this to work.
On my MYSQL table field name for file name is called file_name
varchar 500
I can save the other form data into my database without a problem.
However I can't get the image(s) uploaded.
Following is my image portion of the web form.
Here is the FORM action area
<form method="post" action="php/smartprocess.php" enctype="multipart/form-data" id="smart-form">
My image upload section as following
smartprocess.php section is
<?php
if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
require 'database.php';
include dirname(__FILE__).'/settings/settings.php';
include dirname(__FILE__).'/functions/emailValidation.php';
$TechName = strip_tags(trim($_POST["TechName"]));
$FullAssembly = strip_tags(trim($_POST["FullAssembly"]));
$Notes = strip_tags(trim($_POST["Notes"]));
$SignedDate = strip_tags(trim($_POST["SignedDate"]));
$captcha = strip_tags(trim($_POST["captcha"]));
try {
$q = "INSERT INTO tportal (TechName, FullAssembly, Notes, SignedDate)
VALUES (:TechName, :FullAssembly, :Notes, :SignedDate)";
$query = $conn -> prepare($q);
$results = $query -> execute(array(
":TechName" => $TechName,
":FullAssembly" => $FullAssembly,
":Notes" => $Notes,
":SignedDate" => $SignedDate,
));
if ($conn->query($q)) {
$errors = array();
echo '<div class="alert notification alert-success">Problem has accured please try again.</div>';
//Javascript alert top
/*echo "<script type= 'text/javascript'>alert('Issue adding data');</script>";*/
}
else{
echo '<div class="alert notification alert-success">Your message has been sent successfully!</div>';
//Javascript alert top
/*echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";*/
}
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
if(isset($_POST["captcha"])){
if (!$captcha) {
$errors[] = "You must enter the captcha code";
} else if (($captcha) != $_SESSION['gfm_captcha']) {
$errors[] = "Captcha code is incorrect";
}
}
?>
<div class="section">
<label for="file1" class="field-label">
Upload another image - <span class="small-text fine-grey"> (ONLY JPG : PNG : PDF) </span>
</label>
<label class="field prepend-icon file">
<span class="button btn-primary"> Choose File </span>
<input type="file" class="gui-file" name="image" id="file1"
onChange="document.getElementById('uploader1').value = this.value;">
<input type="text" class="gui-input" id="uploader1" placeholder="no file selected" readonly>
<span class="field-icon"><i class="fa fa-upload"></i></span>
</label>
</div><!-- end section -->
Your help and time is much appreciated.
Sincerely,
Use $_FILES variable of php to help your files uploaded. There is a simple tutorial on file upload in php here
I have a webpage set up that allows for files to be uploaded, the url of the file is saved in the database that works fine, but the file its self is not getting transferred to the server. I am getting a confirmation of the file be saved and the is saving in the database.
Here is a copy of my code.
Any help would be great full.
// Start sessions
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Check to see if the form has been submitted
if (isset($_POST['submit']))
{
// Check to see all fields have been completed
$target = "../documents/memberDocuments/";
$target = $target . basename(str_replace(' ','_',$_FILES['documentsURL']['name']));
$documentsURL =(str_replace(' ','_',$_FILES['documentsURL']['name']));
$documentsDescription = $_POST['documentsDescription'];
$lessonID = $_POST['lessonID'];
if (!empty($documentsDescription) && !empty($documentsURL) && !empty($lessonID))
{
// Create an SQL query to add the comment
$sql = "INSERT INTO tblDocuments (documentsDescription, documentsURL, lessonID) VALUES ('$documentsDescription', '$documentsURL', '$lessonID')";
// Connect to the database
connect();
// Run the query and store the result in a variable
$result = mysql_query($sql) or die("Could not run query");
if(move_uploaded_file($_FILES['documentsURL']['tmp_name'], $target))
// Close connection to the database
mysql_close();
// Check if query was successful
if ($result)
{
$message = '<div class="success"><p>You have added a new lesson.</p><p>Please Click Here to view all modules.</p></div>';
}
else
{
$message = '<div class="error"><p>There was an error adding your record, please try again</p></div>';
}
}
else
{
$message = '<div class="error"><p>Please make sure you fill all fields in before submitting the form.</p></div>';
}
}
?>
<?php
if (isset($message))
{
echo $message;
}
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" form enctype="multipart/form-data">
<fieldset>
<input type="text" name="documentsDescription" class="text" id="documentsDescription" placeholder="Enter The Lessons Number"></br></br>
<input type="file" name="documentsURL" class="text" id="documentsURL" placeholder="Enter The Lesson Description"></br></br>
<input type="text" name="lessonID" class="text" id="lessonID" placeholder="Enter The Module ID Number"></br></br>
<button type="submit" input type="submit" name="submit" id="submit" class="button iconLeft"><i class="email"></i> Submit</button>
</fieldset>
</form>