Saving content of form in array - php

I have a form where names from a SQL-database are listed. After each name there is a textfield for a grade. I want the grades and names to be saved in arrays. It already works with the names, but the array for the grades just gets filled with the content in the last textfield.
$Requete = "SELECT `vorname`, `nachname` FROM `lernende`";
$Result = mysql_query($Requete,$db);
$grade = array();
$vorname = array();
$nachname = array();
$counter = 0;
while($row = mysql_fetch_array($Result))
{
echo '<p>', $row["vorname"]," ", $row["nachname"], " ", '<label>Note: <input type="text" name="note"/></label></p>';
$grade[$counter] = $_POST['note'];
$vorname[$counter] = $row["vorname"];
$nachname[$counter] = $row["nachname"];
$counter = $counter + 1;
}
What is wrong with my code? I've just started learning php and have no idea how to solve this...

You hvae to change this line of code:
echo '<p>', $row["vorname"]," ", $row["nachname"], " ", '<label for="note-'.$counter.'">Note:</label> <input id="note-'.$counter.'" type="text" name="note[]"/></label></p>';
However, your code is not the finest I'd say. Start learning working with arrays as shown on http://php.net/array and start with clean HTML as described at http://de.selfhtml.org/ (since you are German speaking).

Give the grade fields different names, or name them as an array: <input name="note[]">

In your code you have $_POST['note'], which is getting repeated for each row,
for name field and note filed you should be attach $counter to distinguish these input fields.

Related

Making form fields nonempty and calculating averages from form data involving some empty fields using php

I've been trying to:(i) make my form fields nonempty using php scripts and
(ii) calculate average of numerical form data inserted into an array and an element of the array could be empty. For instance, suppose the form is used to harvest students' scores, some student might not offer an optional subject. How to adapt the count() array function in this instance is my headache. I admit that some folks have posed questions that partially addressed it but some issues remain unsolved, hence this post.
In summary:(i) the code below executes even when some form fields are empty, against my wish.(ii) If I grant some form fields to be empty; the result of the average calculation is incorrect; also against my wish
Code:
<?php
$name = $_POST['candidate'];
$Eng_CA = $_POST['Eng_CA'];
$Eng_Ex = $_POST['Eng_Ex'];
$Math_CA = $_POST['Math_CA'];
$Math_Ex = $_POST['Math_Ex'];
$Comp_CA = $_POST['Comp_CA'];
$Comp_Ex = $_POST['Comp_Ex'];
$engSum = $Eng_CA + $Eng_Ex;
$mathSum = $Math_CA + $Math_Ex;
$compSum = $Comp_CA + $Comp_Ex;
$tot = array();
$tot[] = $engSum;
$tot[]= $mathSum;
$tot[] = $compSum;
$total = array_sum($tot);
$Average = $total/count($tot); // Average is incorrcet if some fields are empty
$notEmpty = array();
$notEmpty = array('$name', '$Eng_CA', '$Eng_Ex', '$Math_CA', '$Math_Ex', '$Comp_CA', '$Comp_Ex');
foreach ($notEmpty as $notEmp){ // this is not working; code executes anyway
HTML
<form action ='test_Code.php' method ='post'>
<table width ='600'>
<tr><td> Cand Name</td><td colspan ='2'><input type ='text' name = 'candidate' size = '60'></td></tr>
<th>Subject</th><th>CA</th><th>Exam</th>
<tr><td>Eng</td><td><input type ='text' name = 'Eng_CA'/></td><td><input type ='text' name = 'Eng_Ex'/></td></tr>
<tr><td>Math</td><td><input type ='text' name = 'Math_CA'/></td><td><input type ='text' name = 'Math_Ex'/></td></tr>
<tr><td>Computer</td><td><input type ='text' name = 'Comp_CA'/></td><td><input type ='text' name = 'Comp_Ex'/></td></tr>
if(empty($notEmp)){
echo"You have left some fields empty, fill them pls";
die();
}
}
echo"<table border ='1'>";
echo"<th>Candidate</th><th>Eng Ca</th><th>Eng Ex</th><th>Math Ca</th> <th>Math Ex</th> <th>Comp Ca</th><th>Comp ex</th><th>Total</th><th>Average</th>";
echo"<tr><td>";
echo $name ."</td><td>".$Eng_CA."</td><td>".$Eng_Ex."</td><td>".$Math_CA."</td><td>".$Math_Ex."</td><td>".$Comp_CA."</td><td>". $Comp_Ex."</td><td>".$total."</td><td>".$Average."</td></tr></table>";
?>
Your trying to do a not empty check in an odd way to me. What I would do personally is simply loop through your $_POST vars first. Check them if they are empty. If so die or error out. example:
<?php
if(!empty($_POST)): //this is how trigger the processes for any form
foreach($_POST as $k => $v):
if(empty($v)){
echo $k.' can not be blank.<br>';
$error .= '<div>'.$k.' can not be blank.</div>'; //here is another option...
}
endforeach;
//if you get here now do your averages or whatever you were wanting.
endif;
//anywhere else in your entire php page write this
if($error){echo $error; } //this is a basic check, if error is empty it will be false, if error is not empty above it will print out the fields that
?>

Posting values to database

I am trying to post some values from checkboxes to my database, at the moment it does post a value, but only the last selected value (I currently have 8 checkboxes). Below is what I am using the get the checkboxes:
<?
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name") or die(mysql_error());
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[]'";
echo 'value="' . $result['name'] . '">';
echo " ";
echo $result['name'];
echo "<br>";
}
?>
So they successfully show in my form and I can tick as many as I want however when I check the database, only the last one is showing.
I have been reading around and it seems like I need to store them in an array however this is the bit I am finding hard to understand.
Could anyone help me so that all values selected are shown in the DB and not just the last one?
EDIT: Too long to fit into a comment so here is the code where it adds the values to the DB
<?php
if(isset($_POST['submit']))
{
$date = $_POST['date'];
$score = $_POST['score'];
$attendees = $_POST['attendees'];
$result = mysql_query("INSERT INTO quiz_results (date, score, attendees)
VALUES ('$date','$score','$attendees')",$connect);
echo "<div class='alert alert-info'><b>Event Added!</b> - You'll will now be taken back to the previous page.</div>";
echo "<meta http-equiv=Refresh content=4;url=add-result.php>";
}//end of if($submit).
?>
$attendees = $_POST['attendees'];
$attendees is an array. You can't simply store the PHP array in the database without first transforming it into a string. You could store it as a comma separated list:
if ( is_array($attendees) ) {
$attendees = implode(', ', $attendees);
}
But, what happens when an "attendee" has a name that contains a comma? You could serialize it:
if ( is_array($attendees) ) {
$attendees = serialize($attendees);
}
But, in either case, what happens when you want to filter your data based on attendee? Now you have more problems.
The best way to manage this data (Google: database one-to-many relationships) is to store the attendees in a separate table that looks something like:
quiz_id attendee_id
1 20
1 42
1 50
See my answer at how to select from database based on a match in category? for an example.
Looks like you need to give each checkbox a different name.
$i=0;
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[$i]'";
$i++
...
and I hope $_POST['attendees'] is an array?
Then when you insert into quiz results, you will need to loop through the arrays and insert one row of elements at a time into the database, you cant just insert arrays directly like that and expect each element to automatically take their own row.
Hope it helps, let me know.
View
<?php
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name");
$html = '';
//And we display the results
while($result = mysql_fetch_array( $data )) {
$html .= sprintf( '<input type="checkbox" name="attendees[]" value="%d"> %s' , $result['id'] , $result['name'] );
}
echo $html;
When you post the form...
<?php
$attendees = isset( $_REQUEST['attendees'] ) ? $_REQUEST['attendees'] : null;
if( !is_null($attendees) && is_array($attendees)){
foreach( $attendees as $attendee){
// do something.. with attendee id
}
echo 'Ids: '.implode(', ', $attendees);
}

Add Values of Checked Form Fields & Add Together To Insert Into Database

I have a form that sends the values to insert into the database. Here's the form:
$result = mysqli_query($con, "
SELECT
a.*,
b.*
FROM b_report_week a INNER JOIN b_report_expenses b
ON a.ID = b.ID
WHERE a.TASK_ID = $taskid
");
while ($row = mysqli_fetch_array($result)) {
$invoiceID = $row['ID'];
$mondayBill = $row['MON_BILL'];
$tuesdayBill = $row['TUE_BILL'];
$wednesdayBill = $row['WED_BILL'];
$thursdayBill = $row['THU_BILL'];
$fridayBill = $row['FRI_BILL'];
$weekTotal = $row['MON_BILL'] + $row['TUE_BILL'] + $row['WED_BILL'] + $row['THU_BILL'] + $row['FRI_BILL'];
print "<input type='checkbox' name='rep[]' value='$invoiceID'>Reference Number: $invoiceID<input type='hidden' name='weektotal' value='$weekTotal'><br />";
}
<input type="submit" name="submit" value="submit">
What I want to happen is the values get inserted into one line the database. However I want the week total for each checkbox to be added together and inserted into one of the fields in the database.
I currently have the insert as:
$sql="INSERT into b_sale_order (LID,PERSON_TYPE_ID,PAYED,PRICE)
VALUES
('s1','1','N','VALUE OF THE $weekTotal added together for each checkbox checked)";
So for example, the hidden field 'weektotal' provides a value for each checkbox. Once the checkbox is ticked and the form is submitted they need to be added together and then inserted into the PRICE field.
I'm not sure how to add the checked values together to insert into one field.
Your help would be appreciated.
I've researched more and although this doesn't work, maybe somebody could point me in the right direction:
$array = array($_POST['weektotal']);
foreach ($array as $value) {
$totalweek += $value;
}
Then put the $totalweek in the VALUES section of the insert?
I've also tried:
$totalweek = array_sum($_POST['weektotal']);
But this seems to add all the values together and not individual for the checkboxes that are selected. Any ideas?
so, change HTML to: <input type='hidden' name='weektotal[$invoiceId]' value='$weekTotal'>
now php
$sum = 0;
foreach($_POST['rep'] as $inv_id){
$sum += $_POST['weektotal'][$inv_id];
}

Search Form Ability To Ignore Blank Fields

I have made a HTML search form which creates a query to a MySql database based on the contents of a form. What I would love to do is ignore the search parameter if the user leaves that specific form field empty. There are lots of answers online, especially on this website, but I can't get any of them to work.
I have stripped down my code as much as possible to paste into here:
The HTML input:
<form action="deletesearchresults.php" method="GET">
<p><b>First Part Of Postcode</b>
<input type="text" name="searchpostcode"></b> </p>
<p><b>Category</b>
<input type="text" name="searchfaroukcat"></b>
<input type="submit" value="Search">
</p>
</form>
The PHP results display:
<?php
mysql_connect("myip", "my_username", "my_password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$sql = mysql_query("SELECT * FROM
GoogleBusinessData
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]' LIMIT 0,20");
while($ser = mysql_fetch_array($sql)) {
echo "<p>" . $ser['BusName'] . "</p>";
echo "<p>" . $ser['PostcodePostalTown'] . "</p>";
echo "<p>" . $ser['PostcodeArea'] . "</p>";
echo "<p>" . $ser['FaroukCat'] . "</p>";
echo "<p> --- </p>";
}
?>
This works great until I leave one field blank, in which case it returns no results as it thinks I am asking for results where that field is empty or null, which I don't wat. I want all of the results where that form field is empty.
I tried combining a like % [myfeild] % etc but I only want the results to display exactly what is on the field and not just the ones that contain what is in the field, for example searching for the postcode "TR1" would return results for TR1, TR10, TR11 etc.
I believe I may need an array but after 3 days of trying, I just don't know how to get this done.
Any help would be amazing.
edit: Also, I will be adding up to ten fields to this form eventually and not just the two in this example so please bear this in mind with any suggestions you may have.
try using isset()
example
if(isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]'";
}elseif(isset($_GET[searchpostcode]) && !isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]'";
}elseif(!isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE FaroukCat = '$_GET[searchfaroukcat]'";
}else{
$fields = "";
}
$sql = "SELECT * FROM
GoogleBusinessData $fields
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull LIMIT 0,20";
You do however need to escape your $_GET variables however i would highly recommend using PDO/mysqli prepared statements http://php.net/manual/en/book.pdo.php or http://php.net/manual/en/book.mysqli.php
or try a foreach loop
foreach($_GET as $keys=>$value){
$values .= $keys."='".$value."' and";
}
$values = rtrim($values, " and");
if(trim($values) != "" || trim($values) != NULL){
$query = "WHERE ".$values;
}else{
$values = "";
}
$sql = "SELECT * FROM `test`".$values;

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

Categories