Looping Through Checkboxes while Inside Another Loop - php

I'm having some trouble solving a nested loop. I have a form that sends a series of data to the mysql database. I use a while function and it works correctly. But now I have an checkbox option for each entry, and that's my problem.
The checkbox should be sent to another table, with the id, the series ID and a checkbox per row.
But all I can do is make the answer from the first series repeat through the others.
This is what I want:
Lance 1
Checkbox 1
checkbox 3
checkbox 4
Lance 2
checkbox 2
checkbox 3
Lance 3
checkbox 1
checkbox 2
checkbox 3
This is what I get
Lance 1
Checkbox 1
checkbox 3
checkbox 4
Lance 2
Checkbox 1
checkbox 3
checkbox 4
Lance 3
Checkbox 1
checkbox 3
checkbox 4
My loop code so far:
$i=0;
$elements = count($lance);
while ($i < $elementss) {
$query = "INSERT INTO
mapa_bordo_lance
(id_mb, lance, data_lance, lat, lon, anzol, isca, hora_lan, hora_rec, ave_capt, mm_uso)
VALUES
('$id_mb', '$lance[$i]', '$data_lance[$i]', '$lat[$i]', '$lon[$i]', '$anzol[$i]', '$isca[$i]', '$hora_lan[$i]', '$hora_rec[$i]',
'$ave_capt[$i]', '$mm_uso[$i]')";
$result = mysql_query($query, $link);
$y = 0;
$elementss2 = count($checkbox);
while ( $y < $elements2) {
$query = "INSERT INTO mapa_bordo_mm (id_mb, lance, mm)
VALUES ('$id_mb', '$lance[$y]', '$medida_metiga[$y]')";
$result = mysql_query($query, $link);
$y++;
}
$i++;
}

About the Checkboxes
According to the information presented in your question, comments, and pasted snippets, I have the feeling that you are getting the same Checkbox values for each Lance because in this code:
$y = 0;
$elementss2 = count($checkbox);
while ( $y < $elements2) {
$query = "INSERT INTO mapa_bordo_mm (id_mb, lance, mm)
VALUES ('$id_mb', '$lance[$y]', '$medida_metiga[$y]')";
$result = mysql_query($query, $link);
$y++;
}
it appears that the $medida_metiga[$y] part is only calling the same $medida_metiga (and its array items...) rather than calling the next $medida_metiga0 and $medida_metiga1 parts in your example array (given in this link.)
You may need to find a way to concatenate your $medida_metiga array/key with a number (like 0, 1, ... etc.) kind of like this:$medida_metiga[$y.$some_number_here] in order to find the matching checkboxes. But you may also want to rethink the naming for the $medida_metiga, $medida_metiga0, $medida_metiga1 approach.
For example, instead of:
$medida_metiga
What if you began with:
$medida_metiga0
This would allow you to more easily iterate through the array/keys without having to check if this item has a number at the end or not.
About the SQL
When you have a chance, it would probably be a good idea to check out how to use prepared statements in PHP if for no other reason than to prevent SQL injection. This other answer may give you some tips on getting started with prepared statements.
About the Looping
While while loops can technically work for your purposes, it might be worth using either for or foreach loops in this case, as those sorts of loops can help keep code clean and improve code readability. It might be worth taking a look at this other answer for tips on selecting loops for different applications.
About the Variable Naming
You may have already seen this, but do make sure that your variable names ($elements or $elementss?) match:
$elements = count($lance);
while ($i < $elementss) { ... }
// ...
$elementss2 = count($checkbox);
while ( $y < $elements2) {

Related

Getting value from multiple drop down menus in PHP

Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.

how to get multiple columns from database in one array?

i want that against each numbers, its call_count and duration are saved in single array.. this is my table:
Number Call_count duration
03455919448 4 14
03215350700 2 35
i want somethng like this:
foreach($number as $number1)
{
$data=array($row['call_count']<3,$row['duration']<20,1)
}
basically i want against each number its count and duration are checked for some values and if they meet the condition, display output 1... actually i can do it with simple if-else but as i have to train my dataset for neural network implementaion so all rows must be in one array? can anyone please help me out?
Maybe I don't understand quite well your code, but:
foreach($number as $number1)
$number1 is never used in your foreach :
$data=array($row['call_count']<3,$row['duration']<20,1)
So I guess $number1 is $row.
Second, it would help me if you provide the SQL Statement you are using now.
You could do a query like:
select Number, if(Call_count<3, if(duration<20, 1, 0), 0) as checked from tablename;
This gives you only the number, and 1 if both conditions are met, and 0 otherwise.
After that, in php do a loop (presented in plain mysql* funcions)
$data = array();
while ($row = mysql_fetch_assoc($result)) { // row will be an array with Number and checked as items
$data[] = $row;
}
// at this point you will have all rows in one array, with number and corresponding 1/0 in each item

Multiple Inputs Insert

I have an application that looks like this:
As you can see, each row contains either a group heading (the rows where there is just an input), or a ingredient form (where there is a small input, then a select, then another larger input).
I use Javascript to add the new spans. I use the following PHP to group each ingredient span into an array, determine the order (because each span can be moved to a different order), and insert into my database.
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
$ingredientQTY = $this->input->post('ingredientQTY');
$measurements = $this->input->post('measurements');
$ingredientNAME = $this->input->post('ingredientNAME');
$ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'ingredientamount' => $ingredientQTY[$i],
'ingredientType' => $measurements[$i],
'ingredientname' => $ingredientNAME[$i],
'recipe_id' => $recipe_id,
'order' => $i + 1,
'user_id' => $user_id
);
$sql = "INSERT `ingredients` (`ingredientamount`,`ingredientType`,`ingredientname`, `recipe_id`, `order`, `user_id`) VALUES ";
$coma = '';
foreach ($rows as $oneRow) {
$sql .= $coma."('".implode("','",$oneRow)."')";
$coma = ', ';
}
}
$this->db->query($sql);
break;
}
This works wonders for inserting the ingredient rows. But I'm not sure how to insert group headings (which must be placed in the for loop to keep the order, the $i + 1, going).
I think I've figured out two solutions(though there may be others, and these might not even work):
Have the group heading input field have the same name value as one of the ingredient text fields, and send a hidden value along with it, saying its a group heading?
Send it as different input field with a different name value?
My question is: how can I do this with my current code, and are either of these efficient solutions, or is there an even better solution?
Thanks for all help! If you need more details, just ask!
You could use an empty heading like <input type="hidden" name="groupheading[]" value="product" /> and the open one like <input type="text" name="groupheading[]" value="" />. The first one should be inside the product-span.
This way, you can continue your loop just the way you are doing now. And $_POST['groupheading'][$key] either returns a groupheading or the phrase 'product'. So, in your script it would be:
if($_POST['groupheading'][$key] == "product") {
// insert product
} else {
// insert group heading
}
I think I helped you this morning or yesterday with an answer.. it's still a bit a weird way you are using to get the effect you need. It can be achieved much easier.

Creating a Chart with PHP and MySql

I have a database with the following table:
id value
-----------
1 yes
2 no
3 no
4 maybe
I'm using some simple php to log the choices entered on a poll website. The user selects a radio box and it is entered into the above table. However, I want to make this a little more flexible. I created a simple backend that allowed an admin user to add or delete poll choices. What would I do to show on the frontend the number of votes for each individual choice, when the number of choices is not constant? I know I could do this easily if the poll choices were static but since the backend user will be changing the choices, how could I dynamically display the results?
I am not really sure what you are asking. Is it COUNT you're looking for?
Don't worry about the choices or the number of choices, grab all the votes/choices and iterate through them and add them to an array indiscriminately: http://codepad.org/LWPyuTqj
$total = array();
$votes = array(1=>'yes',2=>'no',3=>'no',4=>'maybe');
foreach($votes as $vote) {
if (!isset($total[$vote]))
$total[$vote] = 1;
else
$total[$vote] += 1;
}
print_r($total);
I would recommend google graph API for this. It is really easy!
http://code.google.com/apis/chart/interactive/docs/gallery/piechart.html
Generate the code dynamically, using the first example on the link above. First select the values. This assuming there is a question ID so you can relate to the question. In this case id 1.
$result = mysql_query('SELECT value,COUNT(*) as num FROM choises WHERE question_id = 1 GROUP BY value');
Then with PHP loop through the data
$results = array();
while ($row = mysql_fetch_assoc($result)){
$results[$row['value']] = $num;
}
With this you can generate the graph:
echo 'data.addRows('.count($results).');';
$i = 0;
foreach ($results as $value => $num){
echo'
data.setValue('.$i.', 0, "'.$value.'");
data.setValue('.$i.', 1, '.$num.');
';
$i++;
}

How can I select a PHP variable that relates to a specific percentage chance?

I'm trying hard to wrap my head around what I'm doing here, but having some difficulty... Any help or direction would be greatly appreciated.
So I have some values in a table I've extracted according to an array (brilliantly named $array) I've predefined. This is how I did it:
foreach ($array as $value) {
$query = "SELECT * FROM b_table WHERE levelname='$value'";
$result = runquery($query);
$num = mysql_numrows($result);
$i=0;
while ($i < 1) {
$evochance=#mysql_result($result,$i,"evochance"); // These values are integers that will add up to 100. So in one example, $evochance would be 60, 15 and 25 if there were 3 values for the 3 $value that were returned.
$i++;
}
Now I can't figure out where to go from here. $evochance represent percentage chances that are linked to each $value.
Say the the favourable 60% one is selected via some function, it will then insert the $value it's linked with into a different table.
I know it won't help, but the most I came up with was:
if (mt_rand(1,100)<$evochance) {
$valid = "True";
}
else {
$valid = "False";
}
echo "$value chance: $evochance ($valid)<br />\n"; // Added just to see the output.
Well this is obviously not what I'm looking for. And I can't really have a dynamic amount of percentages with this method. Plus, this sometimes outputs a False on both and other times a True on both.
So, I'm an amateur learning the ropes and I've had a go at it. Any direction is welcome.
Thanks =)
**Edit 3 (cleaned up):
#cdburgess I'm sorry for my weak explanations; I'm in the process of trying to grasp this too. Hope you can make sense of it.
Example of what's in my array: $array = array('one', 'two', 'three')
Well let's say there are 3 values in $array like above (Though it won't always be 3 every time this script is run). I'm grabbing all records from a table that contain those values in a specific field (called 'levelname'). Since those values are unique to each record, it will only ever pull as many records as there are values. Now each record in that table has a field called evochance. Within that field is a single number between 1 and 100. The 3 records that I queried earlier (Within a foreach ()) will have evochance numbers that sum up to 100. The function I need decides which record I will use based on the 'evochance' number it contains. If it's 99, then I want that to be used 99% of the time this script is run.
HOWEVER... I don't want a simple weighted chance function for a single number. I want it to select which percentage = true out of n percentages (when n = the number of values in the array). This way, the percentage that returns as true will relate to the levelname so that I can select it (Or at least that's what I'm trying to do).
Also, for clarification: The record that's selected will contain unique information in one of its fields (This is one of the unique values from $array that I queried the table with earlier). I then want to UPDATE another table (a_table) with that value.
So you see, the only thing I can't wrap my head around is the percentage chance selection function... It's quite complicated to me, and I might be going about it in a really round-about way, so if there's an alternative way, I'd surely give it a try.
To the answer I've received: I'm giving that a go now and seeing what I can do. Thanks for your input =)**
I think I understand what you are asking. If I understand correctly, the "percentage chance" is how often the record should be selected. In order to determine that, you must actually track when a record is selected by incrementing a value each time the record is used. There is nothing "random" about what you are doing, so a mt_rand() or rand() function is not in order.
Here is what I suggest, if I understood correctly. I will simplify the code for readability:
<?php
$value = 'one'; // this can be turned into an array and looped through
$query1 = "SELECT sum(times_chosen) FROM `b_table` WHERE `levelname` = '$value'";
$count = /* result from $query1 */
$count = $count + 1; // increment the value for this selection
// get the list of items by order of percentage chance highest to lowest
$query2 = "SELECT id, percentage_chance, times_chosen, name FROM `b_table` WHERE `levelname` = '$value' ORDER BY percentage_chance DESC";
$records = /* results from query 2 */
// percentage_chance INT (.01 to 1) 10% to 100%
foreach($records as $row) {
if(ceil($row['percentage_chance'] * $count) > $row['times_chosen']) {
// chose this record to use and increment times_chosen
$selected_record = $row['name'];
$update_query = "UPDATE `b_table` SET times_chosen = times_chosen + 1 WHERE id = $row['id']";
/* run query against DB */
// exit foreach (stop processing records because the selection is made)
break 1;
}
}
// check here to make sure a record was selected, if not, then take record 1 and use it but
// don't forget to increment times_chosen
?>
This should explain itself, but in a nutshell, you are telling the routine to order the database records by the percentage chance highest chance first. Then, if percentage chance is greater than total, skip it and go to the next record.
UPDATE: So, given this set of records:
$records = array(
1 => array(
'id' => 1001, 'percentage_chance' => .67, 'name' => 'Function A', 'times_chosen' => 0,
),
2 => array(
'id' => 1002, 'percentage_chance' => .21, 'name' => 'Function A', 'times_chosen' => 0,
),
3 => array(
'id' => 1003, 'percentage_chance' => .12, 'name' => 'Function A', 'times_chosen' => 0,
)
);
Record 1 will be chosen 67% of the time, record 2 21% of the time, and record 3 12% of the time.
$sum = 0;
$choice = mt_rand(1,100);
foreach ($array as $item) {
$sum += chance($item); // The weight of choosing this item
if ($sum >= $choice) {
// This is the item we have selected
}
}
If I read you right, you want to select one of the items from the array, with some probability of each one being chosen. This method will do that. Make sure the probabilities sum to 100.

Categories