How to update but if field is empty not - php

I need to run a save/update query but only update those fields that aren't empty. My form contains a FILE field and if I don't upload any file then when the save() is executed this field goes blank even if previous data is presented so how can I save/updated but onlye the fields with content to update?
Cheers and thanks in advance

In your model you need to previously test if the data is empty or not and unset it in this case.
if ($this->data['file'] == "") {
unset($this->data['file']);
}

You always can add a condition which checks if the user uploads a file or not.
If not , select the current value in the database for that file and update it with the old value.
For example:
$update['description'] = $_POST['description']; //just another field
if($_POST['file']['name'] == "") //check if there's a new file
$update['filename'] = $this->book->file_name; //current file name
else
$update['filename'] = $_POST['file']['name']; //new file name in case the user uploaded a new file
$this->book->update($update); //update no matter what

Related

If isnt set open txt name else

Essentially what I'm trying to achieve is, if the user hasn't selected one of the dropdown options, then a default .txt is opened, read and displayed. When the user does decide on a drop down option, it echos the users option. It works by getting the value of the option and setting that to a variable to set the open path.
Instead of opening my default which is 'example' when the user hasnt selected, it seems to pick one of the values at random and select it.
If the user hasnt selected an option, the default file path is p-changelog/example.txt
If the user has chosen and option, the file path becomes p-changelog/$userOp.txt (UserOp being the users option from the drop down).
if(!isset($_POST['userDateOp'])) {
$userOp = "example";
}else{
$userOp = $_POST['userDateOp'];
}
if(!isset($_POST['submit'])) {
$changelog = fopen("p-changelog/$userOp.txt", 'r');
$pageTxt = fread($changelog, 25000);
echo nl2br($pageTxt);
}
Entire Page: Code
I am new to PHP before criticising anything I've done.
userDateOp is always going to be set, as its posted every time.
What you are looking for is its value being empty
That function is
if(empty($_POST['userDateOp'])) {
You don't need to check if submit is set because you've already validated the existence of userDateOp. So this will only lead to an undefined variable notice for $changelog for default.
Your simplified script should be
if(!isset($_POST['userDateOp'])) {
$userOp = "example";
}else{
$userOp = $_POST['userDateOp'];
}
$changelog = fopen("p-changelog/$userOp.txt", 'r');
$pageTxt = fread($changelog, 25000);
echo nl2br($pageTxt);

Can I add user ID to the file name in file upload?

I would like to add user ID to file name in file upload. I tried this:
$date=date("Y-m-d");
$id=mysql_insert_id();
//Abstract File codes
$info = pathinfo($_FILES['abstract']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $id."_Abstract.".$ext;
$target = "application/abstracts/"; $target = $target .$newname;
if (empty($ext))
{ $abstract='' ;}
else $abstract=$newname;
But I only get 0 for ID.
I can display $name but $id is not working. Is it because I do not have an input for $id on my form? Thank you. I should also mention that the user is filling out an application form (for the first time) and attaching files on the same page. I had the file upload after the application was submitted I don;t think I would have problem call the $id. But since everything is on one page I might be calling an empty $id.

Adding additional form post fields to a mysql insert script

I have been doing a tutorial on posting to a database with Ajax and now I have it working with 1 form field, but I would like to learn how to get it to work with 2 form fields.
The form field I have working is named content_txt and it is inserted into add_delete_record(content). The second form is named balance_txt and would also be inserted in the same table as content_txt was.
This is the block of code that I'm trying to figure out how to update with the extra form field. I have added notes in it to explain what I am using each thing for and what I want to do:
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
{ //checks $_POST["content_txt"] is not empty, but I am not sure how to add the other field into this
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
//using this to strip stuff from the post, but I am not sure how I should added the other form field to this, should I create another variable line or can I add it to this.
// Insert sanitize string in record and I think I have it correct, except if I need to add a variable following content
if(mysql_query("INSERT INTO add_delete_record(`content`,`balance`) VALUES('".$contentToSave."')"))
{
//This returns the results back to the page, do I need to have a duplicate section for the additional record or will this work like a loop.
$my_id = mysql_insert_id(); //Get ID of last inserted row from MySQL
echo '<li id="item_'.$my_id.'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $contentToSave.'</li>';
mysql_close($connecDB); //close db connection
if you use two form just named same field name "content_txt" and post it .
or when you ajax data change it name on ajax field .

PHP: Properly storing image names in MySQL DB

I am storing images name inside on MySQL database. Everytime I perform an upload, I have it return a link back with the image name attached which then I extract the image name and saved to the database. I have corrections to some critical flaws but I am still facing issues of having blank spaces/ duplicate names inserted into my database even though I have established checkpoints.
How can I avoid duplication/blank spaces of file names?
Is there a better approach in storing names in DB?
Location of image inside webserver:
http://www.example.com/imageupload/uploads/medium/50038dc14afb7.jpg
Link in the browser:
http://www.example.org/imageupload/index.php?i=50038dc14afb7.jpg
PHP
<?
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
$images = explode(',', $_POST['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images) //There were no images to return
return false;
$db = dbConn::getConnection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $db->prepare($sql);
$prepared->execute(array($image));
}
}
?>
First, the blank name issue can perharps be fixed by checking $_POST['i']:
if (!isset($_POST['i'])) {
echo "No image to upload!";
die();
}
Have you tried redirecting after uploading the image?
// When image is uploaded
header("Location: http://example.org/imageupload/index.php");
die();
you can change the image name at the time of upload,
rand() is the function, which return random value, so you can avoid the duplicate image name,
the date time option will return always new date time, so you can diffidently get unique image name
Ex.$imageName.rand().$extention;
OR
Ex. $date = new DateTime(now);
$date = $date->format('Y_m_d_H_i_s');
$imageName.$date.$extention;
a couple of things:
To make sure you have unique file names, use tempnam() (
http://php.net/manual/en/function.tempnam.php )
To avoid page reload issue, post the upload form to a different page, which redirects to a
different page (or the previous form page) after it finishes doing the upload.
This is unrelated to your question but your SQL prepared statement should be outside of the loop.

Create profile picture uploader in zend framework

I have recently started working on zend framework. I want to upload a profile picture and rename & re-size it. Am using the code below. with this am able to upload but am not able to rename and am not getting a way to re-size the uploaded file.
if($this->getRequest()->isPost())
{
if(!$objProfilePictureForm->isValid($_POST))
{
//return $this->render('add');
}
if(!$objProfilePictureForm->profile_pic->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
}
if($objProfilePictureForm->profile_pic->isUploaded())
{
$values = $objProfilePictureForm->getValues();
$source = $objProfilePictureForm->profile_pic->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'new';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="../uploads/'.$new_image_name.'" />';
$objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
To Rename a file while uploading, you will have to add the "Rename-Filter" to your file-form-element. The class is called Zend_Filter_File_Rename.
// Create the form
$form = new Zend_Form();
// Create an configure the file-element
$file = new Zend_Form_Element_File('file');
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files.
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename
$form->addElement($file);
// Submit-Button
$form->addElement(new Zend_Form_Element_Submit('save');
// Process postdata
if($this->_request->isPost())
{
// Get the file and store it within the specified destination with the specified name.
$file->receive();
}
To make the filename dynamically you may name it with a timestamp or something. You may also apply the Rename-filter within your post-data-processing before the call of $file->receive(). This could be useful if you insert a row into a table and want to name the file with the id of the just inserted row.
Since you want to store a profile picture you could get the id of the user from your db and name the pic with that id.

Categories