Dealing with starting index in array - PHP - php

I've got an array of users from a database (I'm working in PHP, using CodeIgniter in Sublime)
I've got a view, that has a select that show display all the users, so in my view, at the top, I have this code (suppose that the arrays has 3 items):
<?php
$optionsUsers = array();
$qtyUsers = count($users); -->
if($qtyUsers > 0){
$optionsUsers[0]['name'] = 'Choose an option';
for($i=0; $i < $qtyUsers; $i++){
$optionsUsers[$i]['id'] = $users[$i]["userId"];
$optionsUsers[$i]['name'] = $users[$i]["username"];
}
}
?>
Then, in the select part, I have this:
<select id="cursadaUsuario">
<?php
$qtyOptionsUsers = count($optionsUsers);
if($qtyOptionsUsers>0){
for($i=0; $i<$qtyOptionsUsers; $i++){
if($i == 0){
echo '<option value="0" disabled selected>Please select an option</option>';
}else{
echo '<option value="'.$optionsUsers[$i]['id'].'">'.$optionsUsers[$i]['name'].'</option>';
}
}
}else{
echo '<option value="">There are no options available</option>';
}
?>
</select>
I've assigned to the $optionsUsers array in [0] the string "Choose an option" because when iterating THAT ARRAY in the select, I wanted to display it as disabled and just iterate the rest of the elements as usual
The problem is that array $users starts in 0 --> I've checked it with a foreach and all the users display are actually there:
foreach ($users as $key => $value){
print_r($users);
});
But I wanted [0] to be the text to display, "Choose your option", so if I assign the text to [0], the first item in array $users is never shown :( (in this example, it would iterate the text and 2 of the items, not the 3)
If I remove the text to [O], and just iterate the array, all the users are shown correctly, no one is missing, but that means... no text to tell "Choose an option" :/
I would like it to look like this --> http://www.hkvstore.com/phpreportmaker/doc/images/dropdownselect.png, so I want the text "Choose you option" to be shown AND disabled, and then the elements of the array, in my case, a list of users.
Note: I would like to keep using a 'for' loop.
Note2: This (Add option selected disabled in PHP) would be kind of similar to what I want to achieve, but still, I don't think I could just change the keys and assign my own to a list of users, the could be changed, added, deleted, etc.. :/
Ideas? Thanks in advance! :)

Unless I'm not understanding you, it's the same as the "No options available" option – it belongs outside the loop:
if ($qtyOptionsUsers > 0) {
echo '<option value="0" disabled selected>Please select an option</option>';
for ($i = 0; $i < $qtyOptionsUsers; $i++) {
echo '<option value="'.$optionsUsers[$i]['id'].'">'.$optionsUsers[$i]['name'].'</option>';
}
} else {
echo '<option value="">There are no options available</option>';
}

you need to push the users data from index 1 rather than from 0 index.Try below code to fix the choose option
for($i=0; $i <= $qtyUsers; $i++){
$optionsUsers[$i+1]['id'] = $users[$i]["userId"];
$optionsUsers[$i+1]['name'] = $users[$i]["username"];
}

Related

input (radio) value consists of ~2000 bytes, is there a better way?

I have a MySQL database that stores items (goods and services), and along with each item, terms (terms and conditions) will also be stored, which can be roughly 2000 bytes.
http://i.imgur.com/7t3cvSE.png
This is my basic set up
$term_options = array();
$term_options[] = "None";
$term_options[] = "massive string containing 2000 bytes or more";
...
foreach ($term_options as $term) {
?>
<label class="term">
<input type="radio" name="terms" value="<?php echo $term; ?>">
<?php echo $term; ?>
</label>
<?php
}
The above code does exactly what I want, but it feels wrong to have a massive value within a radio input (which may contain Unicode characters). Am I wrong to worry?
Before, I used a SELECT menu with option values equal to the index position of each array item:
?>
<select name="terms">
<?php
$i = 0;
for ($i = 0; $i < count($term_options); $i++) {
?>
<option><?php echo $i; ?></option>
<?php
}
?>
</select>
<?php
Then my $_POST would look something like this:
$terms = $term_options[$_POST['terms']];
It worked nicely until it came to my update form which should display the currently selected values. I wasn't sure how to compare the isset value with something generated via array.
It's simple to do this with static values, e.g.:
<option <?php if (isset($row['x']) && $row['x'] === 'x') echo 'selected'; ?>>x</option>
but while creating each option in a foreach loop, I have no idea what to do and the below doesn't work:
<option <?php if (isset($row['x']) && $row['x'] === $term_options[$i]) echo 'selected'; ?>><?php echo $i; ?></option>
$i++;
Yes, you are right in your worries. If this page is going to display many of these items and each item has a massive string like this, the final page is going to be huge. An this page will be sent by your server to the client browser. Bigger the page, bigger the time.
You are retrieving these items from a MySQL database. Each item probably has a primary key. Why don't you just use this primary key as part of the name of the radio buttons and then you may retrieve again just the selected item?
Something like
<input type="radio" name="rb_1">
where this "1" appended to "rb_" is the key of an item. Then you just need to break this string, recover the primary key and search if to recover the huge string.
This may generate another database operation, of course. But this will be nothing when compared with the transmission of a huge page with, say, 100 times 2k items.

PHP Populate dropdown menu values from database

I am a beginner trying to ouptut the values of dropdown menu from a database. I already automatically generate the values from database but the problem i am having is I want the the value that is being selected to be displayed.
Ideally im trying to update a Subject which I want to data to be displayed in an HTML page where each item could be updated. What i need is to be able to select the 'position' of the subject that is beeing selected.
Here is my code:
<p>Position:
<select name="position">
<?php
$sel_subject = get_all_subjects();
$subject_count = mysql_num_rows($sel_subject);
//$subject_count+1 because we are adding a subject
for($count=1; $count <= $subject_count+1; $count++) {
echo "<option value=\"{$count}\"";
if($sel_subject['position'] == $count) {
echo " selected='selected'";
}
echo ">{$count}</option>";
}
?>
</select>
You seem to be relying on $count to be some internal ID that remains static; given that it's just a monotonically advancing integer, this seems like a risky proposition. However, if you're comfortable with that, all you need to do is change the value in the last echo statement to be the subject name instead of $count. I would instead encourage you to use something meaningful to the database - for example, some people create an auto_increment field called subject_id and key off of that; others like to use UUIDs.
I would also generally suggest using a foreach loop instead of a for loop, as it tends to simplify the code (you don't have to worry about maintaining the counter, or creating fence post errors, etc.) Here's a brief example - I'm guessing a bit at what the actual data is that is available to you, hopefully you can extrapolate it to what you actually have.
<p>Position:
<select name="position">
<?php
$sel_subject = get_all_subjects();
foreach($sel_subject as $subject_num => $subject) {
echo '<option value="', $subject_num, '"';
if ($subject['selected']) {
echo 'selected="selected"';
}
echo '>', $subject['subject_name'], '</option>';
}

Changing input format and database issue

I'm tasked with fixing a job information page at work. When someone clicks "edit job" to edit a job, a form of all the database titles and values is listed and they can click on an input box and change it and update. Basic stuff.
Now, in the input box for "Payment terms:" the percentages are written exactly like this, "40/40/20" and so in the database under payment they're listed as 40/40/20.
So the label + input box looks like this, Payment terms: [40/40/20].
<p><label for='payment'>Payment Terms</label><input name='payment'
id='payment' value='<?php if(isset($data2['payment'])) echo
$data2['payment']; ?>' /></p>
I want to change this to 4 drop down boxes where they can pick the percentages, for instance
Payment terms: [40]
[40]
[20]
[empty]
There is a TON of jobs with their own payment terms in the db and I think I may have to add 4 columns to the db instead of just 1 column named payment and values listed as %/%/%/%.
Obviously that doesn't seem like a good solution as it would take forever to fix all the jobs and enter their data for each term into the new columns.
What should I do ?
You can use explode to split the string from your database. Then you can make 4 <select> boxes:
<?php
$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) { ?>
<select>
<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>
<?php } ?>
I put the blank option first as it will be selected by default that way.

Breaking from foreach loop

I'm working on a website wherein rows are generated depending on how many users there are. In this example, I have three users. Basically, I pass data through $_POST using drop down select data. Here's what I'm passing to PHP. These are wrapped in <form> but I cleaned it to show just the important data.
...
<select name="taction[3]" >
<option value="accept">Accept</option>
<select name="taction[4]" >
<option value="accept">Accept</option>
<select name="taction[6]" >
<option value="accept">Accept</option>
...
My php looks like this:
$total = 1;
foreach ($_POST['taction'] as $userid => $action)
{
if ($action == "accept")
{
if ($total<1)
{
break;
}
else
{
echo $userid."foo";
$total = ($total - 1);
}
}
}
For some reason, it is still displaying three "foo's" when it should've stopped after the first "foo". What am I doing wrong?
Change it to
if($total <= 1)
Or start the $total variable at 0.
Thanks for your suggestions. I was at fault by relying on variables outside the foreach statement. I had to copy the operations inside the loop again for it to register the added data.

How to fill in placeholder boxes with a foreach loop?

Using PHP (at if it's need, jquery):
I have this page with 30 boxes. It will never be more, or less.
On those 30 boxes, some of them will be filled with "box specific" data.
How can I say:
If there are 20 records on the foreach to loop trought, then, 20 boxes will contain data, and the rest will stay with the placeholders.
If there are 10 records on the foreach, then 20 boxes will stay with the placeholdes.
How can something like this be achieved ?
Can anyone provide me a good example for doing so?
Thanks a lot,
MEM
Assuming $data is a numerically keyed array of your data:
<?php for($i = 0; $i < 30; $i++): ?>
<?php if(isset($data[$i]): ?>
<!-- the html for a box WITH data -->
<?php else: ?>
<!-- html for an empty placeholder box -->
<?php endif; ?>
<?php endfor;?>
Fill an array with the bits of data you do have, add 30 placeholders, take the first 30 elements of the array, and iterate over those.
Do you have names for each box? Assuming there is some name/id in your 10 or 20 records which I'm assuming are in an array...
function OutputBoxes($records, $boxes){
foreach($boxes as $box){
$box->PopulateWithPlaceHolder();
}
foreach($records as $record){
$box = GetMatchingBox($record);
$box->SetValue($record['valueProperty']);
}
foreach($boxes as $box){
echo $box->ElementHtml();
}
}
Assuming here that you have some type of box object which knows how to output itself as HTML, and set whatever value you would like that is coming from the record.
make an array with all your data. then run a for-loop (0..30) to build your boxes. For each item in your loop, if your box-data array contains an element, then output specific data, otherwise output placeholder data. Something like this...
<?php
$box_data = array(
"data for box 1",
"data for box 2",
"data for box 3"
);
for( $i=0; $i<30; ++$i ) {
if( $i >= count($box_data) ) {
// output "placeholder box"
echo "<div class=\"box placeholder\">Placeholder Box</div>";
} else {
// output the box's specific data
echo "<div class=\"box non-placeholder\">{$box_data[$i]}</div>";
}
}

Categories