Idea for limiting photo uploadby field - php

I have a form with 10 fields of photo upload. What I want to do is to limit 10 photo upload. Ususally after you upload 10 photos and after that the the 10 fields will appear again. But this time I want to make it limitable. For example, there are 10 upload fields and after you upload 5 photos, there will be only 5 fields left. If you delete a photo then 6 fields will apear there. For now, I'm using select count(*) to count number of rows in MySql table and I'm using :
if ($rownumber == 4) {
"show 6 fields"
}
Are there any other method to do this? The method that I'm using now are so complicated and uses codeas a lot.

Why lots of code?
$maxuploadslots = 10;
for($i=0; $i<$maxuploadslots; $i++)
{
if($i < $rownumber)
continue;
echo "<input...."; // I believe you add them this way, right?
// that is "ADD 1 FIELD"
}
the for loop will run ten times, and everytime it checks against the uploaded images count if there i is smaller the rownumber it'll NOT add a new row, else it will.

For names you can concatenate a variable or you can take input for names as an array .

Related

Updating Images Array

I have a table named tabel_foto which has 2 fields inside it, they are
foto (which contains the image's name), and
kondisi (which contains the image's description)
foto and kondisi's field value is from an-imploded multiple image upload. In other words, i have an upload form which it can upload multiple images, and those images are imploded before they are INSERTED into the sql table, like this :
I can show the image from my table as a list like this :
Please ignore it's bad layout, it's just a prototype/experiment before i add a new feature to my site
My question is, how to update those images to my table? I only want to update the image that is changed, i.e :
foto's field value is borobudur.jpg, bromo.jpg, merapi.jpg, prambanan.jpg, if i update the second image (bromo.jpg) from the form, i only want to update the "bromo.jpg" string in the foto field, how do i detect which image is changed on the form in php since the file upload button is a single file upload (not multiple upload) :
for($i = 0; $i < count($xplode_foto); $i++) {
?>
<img src="<?php echo $xplode_foto[$i]; ?>" id="<?php echo $i; ?>">
<input type="file" id="<?php echo $i; ?>" name="foto_kondisi" onChange="previewFotoJalan(this, this.id)">
<?php
}
Thanks in advance, i appreciate any solutions and answers :)
I would strongly suggest you to use a different mysql schema, like this.
photo_id
group_id
kondisi
Also, you can send a ajax request after every picture's upload , and refresh the page (or just a div).
This will make your life easier.. believe me... been there.
Success!!
Considering you save images on table column as img1,img2,img3 and description as desc1,desc2,desc3
and considering you use explode to update image.
you can make change like that:
<?php
$id = $_POST['imgid'];
//get images string from db and save to $x;
$images_array = explode(',', $x);
unset($images_array[$id]);
$y = implode (',', $images_array);
// now save again $y to db as images
//get description string from db and save to $x;
$desc_array = explode(',', $x);
unset($desc_array [$id]);
$y = implode (',', $desc_array);
// now save again $y to db as desc
Hope this help you

Should I create another table column or is there another way I can go about doing this?

I'm having an issue trying to figure out how to solve this problem.
I have a database with a Table that holds job information. There's a column called "Payments" and the values % per payment term are split up here like so: http://i.imgur.com/Y2Lb48e.png
So at the bottom the values will read 40%, 40%, 20%.
In the form, these values are displayed exactly the same as in the database, 40/40/20.
I was tasked with creating 4 option boxes instead with values in each ranging from 10% to 100%. Here's what the code looks like.
<label for='payment'>Payment Terms</label>
<?php
// Create 4 % boxes that add up to %100 for Payment Terms
// Must validate and add up to %100
$selects = 4;
if (isset($data2['payment'])) {
$percentages = explode("/", $data2['payment']);
// Make sure that the array is long enough by adding zeroes to the end
while (count($percentages) < $selects) $percentages[] = 0;
}
else {
$percentages = array_fill(0, $selects, 0);
}
$options = range(10, 100, 10);
for ($i = 0; $i < $selects; ++$i) { ?>
<ul style="list-style-type: none;"><li><select id="paymentSelect">
<option></option>
<?php foreach ($options as $o) { ?>
<option value="<?php echo $i; ?>"
<?php if ($o == $percentages[$i]) echo ' selected="selected"'; ?>>
<?php echo $o; ?>
</option>
<?php } ?>
</select></li></ul>
<?php } ?>
This is what the form looks like now: http://i.imgur.com/2OvDtsn.png
The blue date boxes is what I want to create. Will I have to make a new column in my table? How will I link each percentage to each date since the percentages are already in the table?
You could make a new table in your data base "Payments" and have a foreign key to tie it back to the original table, your payment column and your date column. Then you can have as many payment percents and Dates you would ever want.
I might be tempted to future proof this for 10 options or 20 options or whatever to save always changing the columns in the table. How about you have 4 rows to show your payment terms - pairs for each date and %. If you have multiple possibilities - i.e. several clients with different payment terms then your table should have a client_id. This way you can have some clients with 2 payments, others with 50 - simply by adding rows with fields (client_id, %, date).
Validation is the same and the table much simpler. To retrieve the payment data you are fetching multiple rows that make table building from PHP fairly straightforward too.
Best
Nick

PHP conditional processing required to display rotating banners continuously

I'm trying to do something a little different with a banner rotator.
Below is the script I am using to read two text files (stored on my root directory with .db extensions) to rotate banners on a website. One file holds a counter (FileDB), the other holds the HTML banner code (URLDB).
The URLDB file currently holds six lines of HTML code to display hyperlinked banners.
The following script builds an array and rotates these banners sequentially on the refresh of the page counting from 0 - 5, and it does this perfectly:
<?php
define('FILEDB', '/WORKING DIRECTORY/count.db');
define('URLDB', '/WORKING DIRECTORY/url.db');
function readURLS()
{
$fo = fopen(URLDB, 'r');
if( null == $fo )
return false;
$retval = array();
while (($line = fgets($fo)) !== false)
{
$retval[] = $line;
}
return $retval;
}
$list = readURLS();
if( false === $list )
{
echo "No URLs available";
}
else
{
$fo = fopen(FILEDB, 'a+');
$count = (fread($fo, filesize(FILEDB)) + 1) % count($list);
ftruncate($fo, 0);
fwrite($fo, "{$count}");
fclose($fo);
echo $list[$count];
}
?>
On the webpage that I want to display the banners there are eight placeholders. However I only have six banners.
Here is the PHP code in each of the placeholders:
Placeholder 1: <?php echo $list[$count];?>
Placeholder 2: <?php echo $list[$count +1];?>
Placeholder 3: <?php echo $list[$count +2];?>
Placeholder 4: <?php echo $list[$count +3];?>
Placeholder 5: <?php echo $list[$count +4];?>
Placeholder 6: <?php echo $list[$count +5];?>
Placeholder 7: <?php echo $list[$count +6];?>
Placeholder 8: <?php echo $list[$count +7];?>
With the count at 0 the 6 banners are displayed in placeholders 1 - 6 and placeholders 7 and 8 are blank.
With every refresh the counter is increase by one, showing each banner in the first placed holder and pulling the other banners through each placeholder from 5 through to 0, but leaving previously populated placeholders blank until the sixth banner is in placeholder one. Then on the next refresh banners 1 - 6 are once again shown.
This occurs because I've hardcoded the values in each placeholder and I am obviously attempting to reference an entry in the file that is out of the bounds of the array built by the above script.
You can see a working example here.
What I am trying to achieve is display all banners in the URLDB such that when the last entry is shown, the first entry is displayed in the next placeholder (which in this case is placeholder 7) and the 2nd entry is show in in placeholder 8.
The idea is that the banners move continuously through each of the placeholders like the carriages of a train with each page refresh and increment of the counter - one following the other.
So, now you have the background, on to my question.
Is there a way I can amend the script to store in a PHP variable the maximum number of entries in the URLDB file/array and subsequently add conditional processing in the placeholders to check when the counter reaches this maximum value, and reference the next valid value in the array (i.e. 0) such that the banners restart again in the surplus placeholders - so here are no blank or empty placeholders shown?
I imagine this might seem like a strange request. But of course I would appreciate any advice on how to achieve my goal based on where things are currently.
Once you use a loop things become a bit easier to manipulate.
Hopefully the following solves your problem.
$numOfBanners = count($list);
$numOfPlacements = 8;
for ($i=0; $i < $numOfPlacements; $i++) {
// use the modulus operator to come back around
$bannerID = $i % $numOfBanners;
echo $list[$bannerID];
}
More info on the modulus operator can be found here.

Using For loop to get values of multiple elements in PHP

The title is so general mainly because I don't know what should be the appropriate title for it. Let me just explain the situation:
Say that I have two textboxes named LastName0 and FirstName0 and a button called addMore. When I click addMore, another two textboxes will be created through JavaScript. These textboxes will be named LastName1 and FirstName1. When I click the addMore button again, another two textboxes button will be created and named LastName2 and FirstName2 respectively. This will go on as long as the addMore button is clicked. Also, a button named deleteThis will be created alongside the textboxes. This simply deletes the created textboxes when clicked.
I also initialized a variable called counter. Every time the addMore button is clicked, the counter goes up by 1, and whenever the deleteThis button is clicked, the counter decreases by 1. The value of the counter is stored in a hidden input type.
When the user submits the form, I get the value of the counter and create a For loop to get all the values of the textboxes in the form. Here is the sample code:
//Suppose that the user decides to add 2 more textboxes. Now we have the following:
// LastName0 FirstName0
// LastName1 FirstName1
// LastName2 FirstName2
$ctr = $_POST['counter']; //the counter == 3
for ($x = 0; $x < $ctr; $ctr++)
{
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//This will get the values of LastName0,1,2 and FirstName0,1,2
//code to save to database…
}
On the code above, if the value of counter is equal to 3, then the values of textboxes LastName0,1,2 and FirstName0,1,2 will be saved. Now here is the problem: If the user decided to delete LastName1 and FirstName1, the For loop will not be able to iterate properly:
$ctr = $_POST['counter']; //the counter == 2
for ($x = 0; $x < $ctr; $ctr++)
{
//Only LastName0 and FirstName0 will be saved.
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
Someone told me to use the "push and pop" concept to solve this problem, but I am not really sure on how to apply it here. So if anyone can tell me how to apply it, it'll be grand.
Add your input text boxes with name as array ie, <input type="text" name="FirstName[]" />
In php you can fetch them as a array. ie,
foreach($_POST["FirstName"] as $k=>$val){
echo $val; // give you first name
echo $_POST["LastName"][$k]; // will give you last ame
}
In this case even if one set of field is removed in HTML will not affect the php code.
One solution would be to use the isset function like this:
$ctr = $_POST['counter'];
for ($x = 0; $x < $ctr; $ctr++)
{
isset($_POST["LastName$x"])?$lastname = $_POST["LastName$x"]:;
isset($_POST["FirstName$x"])?$firstname = $_POST["FirstName$x"]:;
}
If it is possible, instead of using LastNameN and FirstNameN names try using LastName[N] and FirstName[N], this way the result is an array and you can iterate through it with a foreach, meaning you will not need the counter and the index of the value will not be important:
foreach ($_POST["LastName"] as $i=>$lastname) {
if (!isset($_POST["FirstName"][$i])) {
// This should only happen if someone messes with the client side before posting
throw new Exception("Last name input does not have a related First name input");
}
$firstname = $_POST["FirstName"][$i];
}
If not, then you may have to use your $counter in a different way
$current = 0;
while ($counter) { // Stop only when i found all
if (isset($_POST["LastName$current"]) {
$counter--; // Found one
$lastname = $_POST["LastName$current"];
$firstname = $_POST["FirstName$current"];
}
$current++;
}
A better way to solve this would be to use arrays for Firstname and Lastname. Instead of calling them Lastname0 and Firstname0, then Lastname1 and Firstname1, call them all Lastname[] and Firstname[]. Give them ID's of Lastname0 and Firstname0 and so on for the delete function, but keep the names as arrays.
When the form is submitted use the following:
foreach($_POST['Lastname'] as $i => $lastname) {
$firstname = $_POST['Firstname'][$i]
//... code to save into the database here
}
Be warned though that in IE if you have an empty field it will not be submitted, so if Lastname0 has a value, but Firstname0 does not, then $_POST['Firstname'][0] will in fact contain the value of Firstname1 (assuming it has a value in it). To get around this you can use javascript to check if a field is empty when submitting the form, and if so put the word EMPTY in it.
Do not use counter if not required
A much easier way is to add array name when admore clicked.
Give a name like first_name[] in textbox
if you create form like that you can use foreach through $_POST['first_name']
try var_dump($_POST) in you php code to see how things goes on.
Inside your for loop, maybe you could try...
if ((isset($_POST["LastName$x"])) && (isset($_POST["FirstName$x"]))){
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
This will check if the variables exists before you try to do anything with them.

Friends List Pagination

I have got a feature on my website called 'View friends' that displays a hidden div containing a users friends. The only problem so far is I would like it so that it would show 7 members on each row for 3 rows so a total of 21 members on each page. I know I will have to round up NumOfMembers/21 giving me the pages needed. I just need some advice in how I should set up the pagination from when thee SQL query gets the total amount of friends. Any ideas?
The SQL-query should use the limit and offset parameters for pagination, depending on the page n you are on, like this:
SELECT .... LIMIT 21 OFFSET n*21
When handling the results, simply use the modulo operator for determining the lines and rows your current result has to be put in:
// where $i is the result number
$row = $i % 7;
$line = $i % 3;
You have 2 options:
First you can load everything from the php in one query and put all users in an array(content), and just display in pages!
content = [];
max = 21;
function handlePaginationClick(page, pagination_container) {
$('#MyContentArea').empty();
for(var i=0;i<max;i++) {
if(null!=content[(page*max)+i]) $('#MyContentArea').append(content[(page*max)+i]);
}
return false;
}
$("#News-Pagination").pagination(content.length, {
items_per_page:max,
callback:handlePaginationClick
});
you can use Jquery Pagination: https://github.com/gbirke/jquery_pagination#readme
for that.
Another approach is still using jquery pagination, but not load everything at once! then you must have same ajax call in the method 'handlePaginationClick' to pull all page information.

Categories