Checkbox values on submit - php

What I want to do is to display values from database on checkbox labels. I already did that part:
$acc = $truckerController->GetAccessory();
$acc_result = "<form action='' method='post'>";
foreach ($acc as $value) {
$id = $value->id;
$device = $value->device;
$acc_result .= "<input type='checkbox' name='$device' id='$device' value='$id'>"
. "<label for='$device'>$device</label> ";
}
$acc_result .= "<input type='submit' name='acc_submit' value='submit'><form/>";
echo $acc_result;
but what I want to accomplish is when submitting checked values I can't seem to get the checked values.
if (isset($_POST["acc_submit"])) {
echo $_POST["$device"];
}
Help please!

Related

showing results obtained after $_POST in a new page

I have been trying to work this out for a while.
I have created a form with a dropdown box that gets results from a database. from this i then $_POST that from to another page. From that second page i wish to get the ID number and then get the records and display them on screen.
I will then put them in a table to organise the results better.
can anyone help me in achieving this.
Here is the code for the form (which works and sends the $PlantID)
$sql = "SELECT DISTINCT * FROM PLANTS";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
//********************* Botannical name drop down box
echo "<form name='selection' id='selection' action='profile.php' method='post'>";
echo "<select name='flower'>";
while($row = mysqli_fetch_array($result)) {
$plantid = $row['FlowerID'];
$plantname = $row['Botannical_Name'];
$plantcommon = $row['Common_Name'];
/* $plantheight = $row['Height'];
$plantav = $row['AV'];
$plantcolours = $row['Colours'];
$plantflowering = $row['Flower_Time'];
$plantspecial = $row['Special_Conditions'];
$plantfrost = $row['Frost_Hardy'];
$plantaspect = $row['Aspect'];
$plantspeed = $row['Growth_Speed'];*/
echo "<option value=".$plantid.">".$plantname." -> AKA -> ".$plantcommon."</option>";
}
echo "</select>";
echo "<br />";
//********************* End of form
echo "<input type='submit' name='submit' value='Submit'/>";
echo "</form>";
I have created this page to get the ID and display that ID on screen. AS you can tell i have probably doubled up on ways to try work this out.
$sql = "SELECT * FROM PLANTS";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
if(isset($_POST['submit'])){
$selected_val = $_POST['Botannical_Name']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
echo "<br />";
echo "well:".$_POST["Botannical_Name"]."<br/>";
echo "now:".$plantquery."<br />";
echo $_POST;
echo "<table>";
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
Any help would be greatly appreciated.
you should use following to get the selected value,
$selected_val = $_POST['flower'];
if(isset($_POST['submit'])){
$selected_val = $_POST['flower']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
$sql = "SELECT * FROM PLANTS WHERE FlowerID='.$selected_val.'";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
while ($row=mysqli_fetch_assoc($result))
{
echo $row['Botannical_Name'];
}
}
echo "<br />";
print_r($_POST);
if(!empty(_POST)) {
echo "<table>";
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
}

foreach loop submit button issue

First of all i start writing php this week and there may be unnecessary lines:)
I'm just trying figuring out the logic. For now everything went fine(thx to stackoverflow). Until,
In my foreach loop statement i put submit button, I added the db id after button name. So i put the id after $_POST too. But the problem is only the first submit button works. When i click the others nothing happens.
Thanks for your help. (btw i tried all other answers for foreach button issues. didn't help)
if (isset($_POST['arama'])) {
$ara = trim(strip_tags($_POST["ara"]));
$duzelt = trim(strip_tags($_POST["duzelt"]));
$id = $_SESSION["id"];
if (!empty($ara)) {
echo '<div class="form-style-10">';
echo '<table><tr>';
echo "<th>İsim</th><th>Cep Telefonu</th><th>Sabit Telefonu</th> </tr>";
$ara1 = '%'.$ara.'%';
$sql = $db -> query("SELECT * FROM rehber WHERE k_id='".$id."' AND isim LIKE '%$ara%'");
$yok = $sql->rowCount();;
if ($yok != 0) {
echo "<form action='' method='POST'>";
foreach ($sql as $dizi) {
$iden=$dizi[id];
echo "<tr><td><input type='text' name='isim1' value='$dizi[isim]'></td>";
echo "<td><input type='text' name='cep1' value='$dizi[cepno]'></td>";
echo "<td><input type='text' name='ev1' value='$dizi[evno]'></td>";
echo "<input type='hidden' name='id2' value='$iden'>";
echo "<td><input type='submit' name='duzelt".$iden."' value='duzelt'></td></form></tr>";
}
echo "</table>";
echo "</div>";
}else{
echo '<div class="form-style-10" style="background-color:#f04"><div class="section" style="color:#FFFC00">'.$ara.' adında bir kullanıcı kayıtlı değildir.</div></div>';
header("refresh:3;rehber.php?mr=arama");
}
}
else{
echo '<div class="form-style-10" style="background-color:#f04"><div class="section" style="color:#FFFC00">Arama kutusu boş. Lütfen aramak istediğiniz kişinin adını yazınız.</div></div>';
header("refresh:3;rehber.php?mr=arama");
}
}
$buton = "duzelt".$_POST["id2"];
if (isset($_POST[$buton]) && $_POST[$buton]) {
$duz = $_POST[$buton];
if (!empty($duz)) {
echo $_POST["isim1"];
echo $_POST["cep1"];
echo $_POST["ev1"];
echo $_POST["id2"];
echo $buton;
$sql1 = $db -> prepare("UPDATE rehber SET isim = ?, cepno = ?, evno = ? WHERE id = ?");
$sql1 -> execute(array($_POST["isim1"], $_POST["cep1"], $_POST["ev1"], $_POST["id2"]));
echo "Kayıt başarıyla tamamlanmıştır.";
header("refresh:3;rehber.php?mr=duzen");
}else{
echo "kaydedilecek veri yok";
}
}
The only real issue that I can see if that the initial form constructor appears outside of the form element, whilst the form element is closed in the foreach loop. I would move the form constructor into the foreach loop. Also, as a secondary, you are using id as a constant value in your $iden constructor. This is easily resolved, but it seems you really want the index, which you can get from the foreach loop.
Please observe:
foreach ($sql as $iden => $dizi) { // <-- $iden is now the index
//$iden=$dizi[id]; <- no longer required
echo "<form action='' method='POST'>"; // <--form created inside loop
echo "<tr><td><input type='text' name='isim1' value='$dizi[isim]'></td>";
echo "<td><input type='text' name='cep1' value='$dizi[cepno]'></td>";
echo "<td><input type='text' name='ev1' value='$dizi[evno]'></td>";
echo "<input type='hidden' name='id2' value='$iden'>";
echo "<td><input type='submit' name='duzelt".$iden."' value='duzelt'></td></form></tr>";
}
Now you have the form being constructed within the loop, and the index is properly being passed along.

How to call a PHP function on HTML form submission?

I am having some trouble sending data from a form to a function
Here is my form:
echo "<form id='AddCompany' action='' method=post>";
echo "<table>";
echo "<tr>";
echo "<th colspan='2'>Opret nyt firma</th>";
echo "</tr>";
echo "<td>Firma Navn:<td><input type='text' name='Name' /></td>";
echo "</td></tr>";
echo "<td>Adresse:<td><input type='text' name='Address' /></td>";
echo "</td></tr>";
echo "<td>Postnr.:<td><input type='text' name='Zipcode' /></td>";
echo "</td></tr>";
echo "<td>By:<td><input type='text' name='City' /></td>";
echo "</td></tr>";
echo "<td>Land:<td><input type='text' name='Country' /></td>";
echo "</td></tr>";
echo "<td>Tlf:<td><input type='text' name='Phone' /></td>";
echo "</td></tr>";
echo "<td>Slogan:<td><input type='text' name='Slogan' /></td>";
echo "</td></tr>";
echo "<td>Catch All Email:<td><input type='text' name='Email' /></td>";
echo "</td></tr>";
echo "<td>Logo 1:<td><input type='FILE' name='Logo1' /></td>";
echo "</td></tr>";
echo "<td>Lille Logo:<td><input type='FILE' name='SmallLogo' /></td>";
echo "</td></tr>";
echo "<td>Logo 2:<td><input type='FILE' name='Logo2' /></td>";
echo "</td></tr>";
echo "<td colspan='2'><input type='submit' value='Opret Firma' />";
echo "</form>";
echo "</td></tr>";
echo "</tr>";
echo "</table>";
I want to send the data to this function
function insertRecord ($fieldarray)
{
$this->errors = array();
global $dbconnect, $query;
$dbconnect = db_connect($this->dbname) or trigger_error("SQL", E_USER_ERROR);
$fieldlist = $this->fieldlist;
foreach ($fieldarray as $field => $fieldvalue) {
if (!in_array($field, $fieldlist)) {
unset ($fieldarray[$field]);
} // if
} // foreach
$query = "INSERT INTO $this->tablename SET ";
foreach ($fieldarray as $item => $value) {
$query .= "$item='$value', ";
} // foreach
$query = rtrim($query, ', ');
return;
} // insertRecord
I just realised you might need this bit of code also:
class Company extends Default_Table
{
// additional class variables go here
function __construct ()
{
$this->tablename = 'Company';
$this->dbname = 'oop';
$this->rows_per_page = 15;
$this->fieldlist = array('ID', 'Name', 'Address','Zipcode','City','Country','Phone','Slogan','CatchAllEmail','Logo1','LogoSmall','Logo2');
$this->fieldlist['ID'] = array('pkey' => 'y');
} // __construct
} // Company
Where do I call the function and which variables should I send with it?
I have tried onclick=insertRecord() which doesn't seem to work, and I am thinking it is because I need to insert a variable, which I think needs to be an array of the form data as the function is declared with an array.
As you can see I am pretty much a tenderfoot at this.
I have found out the following:
If I echo my $query after the foreach loop in the insertRecord function I see the query like so:
INSERT INTO Company SET Name='1', Address='2', Zipcode='3', City='4', Country='5', Phone='6', Slogan='7', CatchAllEmail='8', Logo1='', LogoSmall='', Logo2=''
However still nothing is being inserted, I have tried this on 2 servers and with users I know have insert rights however nothing is getting inserted.
No need to use function but you can do like,
remove action ="" from <form>.
then check like,
if($_POST){
//your function logic
// get variable data like
echo $_POST["Name"];
}
Enjoy!
Please take this in the most friendly way, I recommend that you pick up a book or read a tutorial about PHP/MySQL/HTML/JavaScript.
I'll do my best to explain this without going outside the scope of this Q&A site.
What you have in the first part of the code is an HTML form echoed by a PHP script, so the HTML form is now in the client's browser.
What you're trying to do with onclick=insertRecord() is binding an event handler written in PHP (server side) to an event fired in browser (client side).
How to solve your problem?
You need to POST this form to the PHP script containing the insertRecord() function. First you need to modify the action attribute in your <form> and point it to the .php script that has this function, then you simply do something like this:
$cmpny = new Company();
$cmpny->insertRecord($_POST);
You need to have some way of getting your POST data into the $fieldarray. Could be something as simple as:
function insertRecord ($fieldarray) {
//the function you have above
}
insertRecord($_POST);
Of course this is depending on how the insertRecord function is set up to work and if it will recognize all the POST data in the way you have things set up.

Updating MYSQL DB with checkbox and textarea data (in PHP)

I'm using a table to update a database, the table has 264 checkboxes which can be checked and unchecked then updated on the database.
I'm doing this by posting data on the form, using a while loop to set all fields to blank ( the value of the checkbox and the textarea value) for each respective field, then using a foreach loop to update each row in the database with the value of the checkbox.
Now, what I want to do is add the textarea value for each ticked checkbox into the database as well, what i cant figure out is how to do this?
This is my update code:
if (isset($_POST["update"])) {
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2)) {
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
$item = $_POST;
foreach($item as $key => $value) {
$wsID = str_replace("checkbox","",$key);
if (is_numeric($wsID)) {
$updateWSQ = "UPDATE seo_work SET taskValue=$value taskInfo=$value WHERE worksheetID=$wsID AND userID=$userID";
mysql_query($updateWSQ) or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}
}
This is checkbox and textarea code: (please note this is within a form)
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id=checkbox'".$worksheetID."' checked='checked' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id='checkbox".$worksheetID."' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
Use your HTML form like shown below.
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' checked='checked' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
See the modified name and id of your textarea and checkbox. I have modified it to textarea[SOME_WORKSHEET_ID] and checkbox[SOME_WORKSHEET_ID] respectively.
So, when you submit the form, you will receive those checkbox and textarea value as an array, with worksheetId as an index. You can use this [] technique to retrieve the values of the textarea and checkbox, or as many field you want to add in form.
Use above HTML structure and check the $_POST array.
Hope this will help..
Thanks!
Hussain.
You should be able to get the value in the textarea using $_POST['textarea' . $wsID] after your call to is_numeric.
Here is another approach, not completely tested, but hopefully you get the idea...
if (isset($_POST["update"]))
{
// All to blank
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2))
{
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
// Re use your result from the select to go through all the known IDs
foreach($seolistRow2 as $i => $data)
{
// Obtain the ID
$id = $data['worksheetID'];
// Get the checkbox value for current ID
$checkbox_wsID = $_POST['checkbox' . $id];
// Get the textarea value for current ID
$textarea_wsID = $_POST['textarea' . $id];
// Update the Row using mysql_escape
$updateWSQ = "UPDATE seo_work " .
"SET taskValue = '" . mysql_escape_string($checkbox_wsID) ."' taskInfo = '" . mysql_escape_string($textarea_wsID) ."'" .
"WHERE worksheetID=$id AND userID=$userID";
mysql_query($updateWSQ)
or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}

How can I send over multiple check box checks in POST to be deleted from a database?

I've been trying think of a way to do this. I want it to where users can check off items, hit submit and it goes to the code on the next page and deletes all of the checked items from the database. Problem one is that in the post its only sending over the last checked item. Here is how I have it set up right now.
echo "<form name='fm1' METHOD ='POST' ACTION ='displaydelete.php' > ";
//Draws up the table headers
echo "";
echo "";
echo "Fund Number ";
echo "Hours ";
echo "Percentage";
echo "Delete";
echo "";
//While there are query results data is pushed into table cells
while ($row = mysql_fetch_array($queryResult2))
{
$hours = $row['hours'];
$percentage = $hours / 160 * 100;
echo "<tr>";
echo "<td>";
echo $row['funnumber'];
echo "</td>";
echo "<td>";
echo $hours;
echo "</td>";
echo "<td>";
echo $percentage ."%";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='id' value='$row[id]'/>";
echo "</td>";
echo "</tr>";
}
//End of tabel
echo "</table>";
echo" ";
echo "";
What I would like to do is push all of the items into a variable and maybe delete them that way. I'm not really sure how you would handle multiple deletes. I'm doing my delete like this for something else if this helps any.
$query = "DELETE FROM users
WHERE ninenumber = '$ninenumber'";
$result = mysql_query($query)
or die("Query Failed: " .mysql_error());
mysql_close($conn);
In your form:
<input type='checkbox' name='id[]' value='$row[id]'/>
Then, in the file you post to:
if(is_array($_POST['id'])){
foreach($_POST['id'] as $id){
...do something to $id;
}
}
Instead of this:
echo "<input type='checkbox' name='id' value='$row[id]'/>";
You need this:
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
Note the difference. I added [] after the input name. This tells the client and server that there are multiple inputs with that name. $_POST['id'] will be an array you can loop through on the next page.
foreach ($_POST['id'] as $checkbox) {
// DELETE FROM users WHERE ninenumber = $checkbox
}
isset, is_array, and mysql_real_escape_string omitted for brevity.
In the form-generating code, make the name in the html have" []" after it:
...
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
...
Then, in the form-reading code, your post'ed id will be an array.
$id_array = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : array();
foreach( $id_array as $id ) {
$query = "DELETE FROM users WHERE ninenumber = '" . mysql_real_escape_string($id) . "'";
// execute the delete query
}
Putting [] after the name of a control will turn it into an array in the superglobal that you can then iterate over to get all the values from.
You need to have the same name for all of your checkboxes, then all values are passed as array POST variable.
<input type='checkbox' name='id[]' value='$row[id]'/>
Change
name=id
to
name=id[]
this will then give you an array.

Categories