Get output when submit dropdown form - php

I'm making a dropdown menu with information out of my database. It has to get different brands in my dropdown and when selecting a brand and submit search it will show information about that brand. It gets the brands correct from the database but after submit it only shows my last brand. Can somebody help me out... Here is my dropdown menu and search (submit) code:
<div class="bandwielkolom">
<form action="index.php?lang=nl&p=<?php echo $_GET['p']; ?>#keuze" method="post">
<table class="bandentabel">
<tr>
<th colspan="2">Op merk zoeken<a name="band"></a></th>
</tr>
<tr>
<td>Merk:</td>
<td>
<select name="band_merk">
<option value="0">- Merk -</option>
<?php
$wielen = $wielclass->getMerkenWielen($website);
foreach($wielen as $wiel)
{
echo "\t\t\t\t\t\t\t\t\t\t\t<option value=\"".$wiel->merk_code."\"";
if(isset($_GET['search']) && $_GET['search'] == "band" && isset($_GET['wiel']) && $_GET['wiel'] == $wiel->merk_code || isset($_POST['band_submit']) && $_POST['band_merk'] == $wiel->merk_code) { echo " selected=\"selected\""; }
echo ">".$wiel->merk_naam."</option>\n";
}
?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="band_submit" value="Zoek"/></td>
</tr>
</table>
</form>
</div>
This is my class:
Class:
<?php
class wielen extends connect {
private $wielenlijst;
public function getMerkenWielen($database) {
$sql = "SELECT * FROM ".$database."_wielen ORDER BY merk_nummer";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute();
$this->wielenlijst = $stmt->fetchAll(PDO::FETCH_OBJ);
$stmt->closeCursor();
return $this->wielenlijst;
}
catch (Exception $e) {
die ($e->getMessage());
}
}
public function __construct($dbo) {
parent::__construct($dbo);
}
}
?>
This only show the last brand after submit:
<?php
if(isset($_POST['band_submit']))
echo $wiel->merk_naam;
?>
Can somebody help me with this because I cant get it to work
Maybe a fresh look at it will help
thnx for any help
UPDATE:
I got this peace of code now and I will explain what is happening and what I want:
<div class="bandwielkolom">
<form action="index.php?lang=nl&p=<?php echo $_GET['p']; ?>#keuze" method="post">
<table class="bandentabel">
<tr>
<th colspan="2">Op merk zoeken<a name="band"></a></th>
</tr>
<tr>
<td>Merk:</td>
<td>
<select name="band_merk">
<option value="0">- Merk -</option>
<?php
$wielen = $wielclass->getMerkenWielen($website);
$get_wiel = isset($_GET['wiel']) ? $_GET['wiel'] : '';
$post_wiel = isset($_POST['band_merk']) ? $_POST['band_merk'] : '';
foreach($wielen as $wiel) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$selected = $post_wiel['wiel'] === $wiel->merk_code ? ' selected="selected"' : '' ;
}
else {
$selected = $get_wiel['wiel'] === $wiel->merk_code ? ' selected="selected"' : '' ;
}
echo '\t\t\t\t\t\t\t\t\t\t\t<option value="' . $wiel->merk_code . '"' . $selected . '>' . $wiel->merk_naam . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="band_submit" value="Zoek"/></td>
</tr>
</table>
</form>
</div>
<?php
if(isset($_POST['band_submit']) && $_POST['band_merk'] == $wiel->merk_code)
echo $wiel->merk_naam;
?>
Precess code:
if(isset($_POST['band_submit']) && $_POST['band_merk'] == $wiel->merk_code)
echo $wiel->merk_naam;
I get a selectbox with four options out of my database so that is working correct. These options has data in it like a picture and text. When I select one and press submit he has to show the information of the selected option and that should stay selected.
What is happening now is that when I select a option and press submit nothing happens... The button is working but I dont get any output of the selected option and it wont stay selected.
Doing something wrong but I cant figure out what
Any help is welcome:)

You need to use your for loop again to list them all.
foreach($wielen as $wiel)
{
echo $wiel->merk_naam;
}

Related

Data updated in the database even after successfully executing the method

I'm trying to update a cross join table which has three columns. The first column studyID will be the same for all the ten row but heuristicID will be 1 to 10 for each row. Third column is h_priority which has only three values either l, m or h. I have retrieved the data and show it inside a table using a while loop in PHP so that all the 10 rows for that particular studyID is shown. The h_priority data is shown inside a select option. When I click the submit button it should update the h_priority column by checking the combination of studyID and heuristicID in the cross join table but for some reason it is not updating anything in the database at the same time "Priority updated successfully" message comes in. Below is the method I used inside the class.
public function updatePriority($studyID, $heuristicID, $h_priority) {
$query = "UPDATE heuristic_priority SET h_priority = ? WHERE studyID = ? AND heuristicID = ?";
$stmt = $this->upc->prepare($query);
$stmt->bind_param("iis", $studyID, $heuristicID, $h_priority);
if ($stmt->execute()) {
return true;
}
else {
return false;
}
}
This is the code for the table
<?php
include_once '../classes/heuristics.php';
$fetchdata=new Heuristic();
$sql=$fetchdata->h_get_priority($passed_studyID);
$cnt=1;
while($row=mysqli_fetch_array($sql))
{
echo '
<tr>
<td id=id'.$cnt.'>
<div class="hide-heuristicid">
<input type="text" name="studyid[]" value="'.$row['studyID'].'" required>
</div>
</td>
<td id=id'.$cnt.'>
<div class="hide-heuristicid">
<input type="text" name="heuristicid[]" value="'.$row['heuristicID'].'" required>
</div>
</td>
<td id=id'.$cnt.'>
<div>
'.$row['h_title'].'
</div>
</td>
<td id=name'.$cnt.'>
<div>
<select name="priority[]">
<option value="'.$row['h_priority'].'" '.($row['h_priority'] == 'l' ? 'selected' : '').'>Low</option>
<option value="'.$row['h_priority'].'" '.($row['h_priority'] == 'm' ? 'selected' : '').'>Medium</option>
<option value="'.$row['h_priority'].'" '.($row['h_priority'] == 'h' ? 'selected' : '').'>High</option>
</select>
</div>
</td>
</tr>
';
}
?>
This is the PHP code
if (isset($_POST['submit'])) {
$studyID = isset($_POST['studyID[]']) ? $_POST['studyID[]'] : '';
$heuristicID = isset($_POST['heuristicID[]']) ? $_POST['heuristicID[]'] : '';
$h_priority = isset($_POST['h_priority[]']) ? $_POST['h_priority[]'] : '';
$updatePriority = new Heuristic();
if ($updatePriority->updatePriority($studyID, $heuristicID, $h_priority)) {
echo "Priority updated successfully";
}
else {
echo "Failed to update priority";
}
}

PHP Pass Checkbox values and dropdown values to Next Page POST

Iam trying a solution in PHP/MYSQL where in there is a some country list with a checkbox. Certain countries have something called entities which is a drop down which shows Micro, Small, Large as a dropdown. This entity dropdown appears for certain countries only. I am able to pass the checkbox checked values to next page. But i need to pass the value of the entity selected in the drop down also. Iam not able to acheieve that. My code ie posted below. Here i need to pass the value of the drop down (select - entity_selected) also to next page:
<?php
echo '<table border="1">';
while($row1 = mysqli_fetch_array($result_country)) {
$country1 = $row1["country"];
$entity1 = $row1["entity"];
echo '<tr>';
?>
<td><input name="check_list[]" type="checkbox" value="<?php echo $country1;?>"> <?php echo $country1;?></td>
<td>
<?php
if($entity1 == 'Yes'){ ?>
<select class="form-control selectpicker" name="entity_selected">
<option value="Micro">Micro</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
<?php }
?>
</td>
<?php echo '</tr>'; } ?>
</table>
The Next page code is below to get the check box selected countries.
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check;
}
}
How can i get the drop down values here? iam getting the checkbox (countries values correctly). Can anyone pls help me on this pls?
<form method="POST" action="nextpage.php">
<table border="1">
<?php
$i = 0;
while($row1 = mysqli_fetch_array($result_country)) {
$country1 = $row1['country'];
$entity1 = $row1['entity'];
echo "<tr>";
?>
<td>
<input name="check_list<?=$i ?>" type="checkbox" value="<?php echo $country1;?>"> <?php echo $country1;?>
</td>
<td>
<?php
if($entity1=="Yes") {
?>
<select class="form-control selectpicker" name="entity_selected<?=$i ?>">
<option value="Micro">Micro</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
<?php
};
?>
</td>
<?php
$i++;
echo "</tr>";
};
?>
</table>
</form>
nextpage.php:
<?php
$entities = $checklist = [];
foreach($_POST as $k => $v) {
if(preg_match("/^checklist(\d+)$/", $k, $matches))
$checklist[intval($matches[0])] = $v;
unset($matches);
if(preg_match("/^entity_selected(\d+)$/", $k, $matches))
$entities[intval($matches[0])] = $v;
};
?>

Update the value from table in textbox BUT not updated the value in db?

I have listed all the data(Item, Category, Job, Hole(Hole is evaluating marks)) and I display the Hole(mark) in textbox filed.
I want to update the Hole(marks) after user change.
I list all the data using php
<?php
try{
$con = new PDO("mysql:host=localhost;dbname=gcmes", "root", "");
$sql = $con->query("SELECT * FROM details");
echo"<table class='info' align='center'>";
echo"<tr><td width='10'><b>No</b></td>
<td width='30'><b>Category</b></td>
<td width='50'><b>Job</b></td>
<td width='40'><b>Evaluate</b></td><tr>";
foreach($sql as $row) {
$Item = $row["Item"];
$Category = $row["Category"];
$Job = $row["Job"];
$Evaluate = $row["Hole 1"];
echo'
<tr>
<td>' . $Item . '</td>
<td>' . $Category . '</td>
<td>' . $Job . '</td>
<td><input type="input" name="Evaluate" id="Evaluate" value="' . $Evaluate . '">
</td>
</tr>
';
}
echo"</table></form>";
if(isset($_POST['Update_btn'])){
$Evaluate = $_POST["Hole 1"];
if(empty(Evaluate)){
echo "<script type='text/javascript'>alert('Please fill in the required fields to update!')</script>";
}
else{
$insert=$con->prepare("UPDATE details SET Evaluate=:Hole 1 WHERE Item=:Item");
$insert->bindParam(':Hole1',$Evaluate);
$insert->bindParam(":Item",$Item);
$insert->execute();
echo "<script type='text/javascript'>alert('Successful Updated ! ');
window.location.href = 'Hole 1.php';
</script>";
}//else
}//if add button
}//try
catch(PDOException $e)
{
echo "error".$e->getMessage();
}
?>
The html code i just use to display button
<form id="form1" name="Hole 1" method="post" action="Hole 1.php">
<input name="Update_btn" type="image" id="Update_btn" onmouseover="this.src='UpdateO.png'" onmouseout="this.src='UpdateD.png'" value="submit" src="UpdateD.png" alt="submit Button" align="right">
</form>
The problem is will alert message successful updated BUT the value not update in my db. Why? what is the problem?
this is my interface
i want update the marks in textbox filed
I need to change the hole as a selection give the user choose which hole that need to update only, i set the hole have a drop-down menu list. How to dectect which hole?
i just add the code after <td>{$rowData['Frequency']}</td> (dn Fer answer)
<td><select name="hole">
<option value="Hole1">1</option>
<option value="Hole2">2</option>
<option value="Hole3">3</option>
<option value="Hole4">4</option>
<option value="Hole5">5</option>
<option value="Hole6">6</option>
<option value="Hole7">7</option>
<option value="Hole8">8</option>
<option value="Hole9">9</option>
<option value="Hole10">10</option>
<option value="Hole11">11</option>
<option value="Hole12">12</option>
<option value="Hole13">13</option>
<option value="Hole14">14</option>
<option value="Hole15">15</option>
<option value="Hole16">16</option>
<option value="Hole17">17</option>
<option value="Hole18">18</option>
</select>
Keep the following in mind:
I don't have the same environment as yours, so it might not work one
on one.
Spaces in database fieldNames and arrayKeys, etc. are discouraged. I
prefer to use lowerCamelCase, check if dB fieldNames match the code
below!
Read the comments I've placed in the code.
I didn't take psr coding, value validation or safety (sql injection), etc. in consideration. The code is to guide you, you should take these things in consideration yourself.
Hopefully getting you closer to your goals...
Update: The values of the Evaluate field of each row is now validated to be an integer in the range from 1 to 5.
<?php
//Initialize variables
$result = '';
$doUpdate = isset($_POST['updateButton_x']);
//Because button type is 'image', we get parameters buttonName_x and buttonName_y
//from the browsers POST request when the form is sent.
if ($doUpdate) {
//Update button pressed.
//Initialize variables
$stmtSetParams = $stmtInParams = array();
$validationOptions = array('options' => array('min_range' => 1, 'max_range' => 5));
//Define statement and parameters (Assuming dB field 'item' is the primary key).
$set = '`hole1` = CASE `item` ';
foreach ($_POST['evaluate'] as $item => $hole1) {
//Get input value of each table row
if (filter_var($hole1, FILTER_VALIDATE_INT, $validationOptions) !== false) {
//Field is not blank
$set .= 'WHEN ? THEN ? ';
$stmtSetParams[] = $stmtInParams[] = $item;
$stmtSetParams[] = $hole1;
} else {
//Field is not an integer from 1 to 5
$result .= "Field \'Evaluate\' of item \'$item\' with a value of \'$hole1\' is not from 1 to 5 and skipped while saving!\\n";
}
}
$set .= 'END';
//Define query placeholders
$placeHolders = implode(', ', array_fill(0, count($stmtInParams), '?'));
$query = <<<SQL
UPDATE `details` SET $set WHERE `item` IN ($placeHolders)
SQL;
}
//Query the dB.
try {
$dbh = new PDO('mysql:host=localhost;dbname=gcmes', 'root');
if ($doUpdate) {
//Update requested. Prepare and execute update query
$stmt = $dbh->prepare($query);
$stmt->execute(array_merge($stmtSetParams, $stmtInParams));
$result .= 'Update Completed!';
}
//Query for en fetch (updated) table data
$stmt = $dbh->query("SELECT * FROM `details`");
$tableData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
//A PDO exception is raised
$result = 'Error: ' . addslashes($e->getMessage());
}
//Alert results of database operations
if ($result != '') {
echo "<script>alert('$result')</script>";
}
?>
<form id="form1" name="chooseFormNameIfNeeded" method="post" action="test.php">
<!-- attribute align is deprecated, define and use a class instead -->
<table class="info align-center">
<tr>
<!-- use th instead of td for table header -->
<!-- using <b> tag is discouraged -->
<th width="10"><b>No</b></th>
<th width="30"><b>Category</b></th>
<th width="50"><b>Job</b></th>
<th width="40"><b>Evaluate</b></th>
</tr>
<?php
foreach ($tableData as $rowData) {
//Print a table row for each of the fetched records
echo <<<HTML
<tr>
<td>{$rowData['item']}</td>
<td>{$rowData['category']}</td>
<td>{$rowData['job']}</td>
<td>
<!-- Assuming dB field 'item' is the primary key. -->
<input type="number" name="evaluate[{$rowData['item']}]" id="Evaluate" value="{$rowData['hole1']}"
min=1 max=5
>
</td>
</tr>
HTML;
}
?>
</table>
<!-- Attribute align is deprecated, define and use a class instead -->
<!-- Value attribute should not be specified -->
<input name="updateButton" type="image" id="Update_btn" src="http://via.placeholder.com/100x50/0000FF?text=Update"
alt="submit Button" class="align-right"
onmouseover="this.src='http://via.placeholder.com/100x50/00FF00?text=Update'"
onmouseout="this.src='http://via.placeholder.com/100x50/0000FF?text=Update'"
>
</form>

MySQL php edition table and adding the same value on another table

I actually developping an intranet solution for my work,
The thing is that i want to update and operation and add the same result into one of my 3 different tables depending on the -operation- option,
in my initial code if the modification is ok the data will be updated into "taches_redaction" table,
in revenche i need to add 3 different rules,
soif operation is equal to 1 up date taches_redction and add the data into copie table,
soif operation is equal to 2 up date taches_redction and add the data into colla table,
soif operation is equal to 3 up date taches_redction and add the data into archive table,
all of this to have a precise historical record on echa changes in my operations and have some values to get statistics for each team member on the company...
<?php
include '../theme/header-global.php';
?>
<?php
/*
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, $error)
{
?>
<div style="width:100%">
<center><h1>تحيين التوزيع</h1></center>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="serie" value="<?php echo $serie; ?>" readonly="readonly" />
<table cellpadding="3" cellpadding="3" align="center" id=MyTable width="650">
<tr>
<td align="center">الإسم</td>
<td align="center">
<?php
// get results from database
$usage = mysql_query("SELECT t.* , o.* FROM users t,taches_redaction o WHERE t.id=o.user_id GROUP BY user_name")
or die(mysql_error());
while($row = mysql_fetch_assoc( $usage )) {
if($row['user_id'] == $user_id)
{ // echo out the contents of each row into a table
echo '' . $row['user_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<td>
<select id="user_id" name="user_id">
<option value="0"></option>
<?php
$sql = mysql_query('SELECT * FROM users');
while($row = mysql_fetch_array($sql)){
if($row['id'] == $user_id)
{
echo '<option value=' . $row['id'] . ' selected=selected>' . $row['user_name'] . '</option>';
} else {
// do something else
echo '<option value=' . $row['id'] . '>' . $row['user_name'] . '</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td align="center">اليومية</td>
<td align="center"><input type="text" name="journee" value="<?php echo $journee; ?>" /></td>
<td></td>
</tr>
<tr>
<td align="center">الرسم العقاري</td>
<td align="center">
<input type="text" name="titre" value="<?php echo $titre; ?>" />
<?php if (!empty($region) && $region == '4' ) echo 'FR'; ?>
<?php if (!empty($region) && $region == '1') echo 'بن عروس'; ?>
<?php if (!empty($region) && $region == '2') echo 'زغوان'; ?>
<?php if (!empty($region) && $region == '3') echo 'تونس'; ?>
</td>
<td>
<select name="region">
<option value="4" <?php if (!empty($region) && $region == '4' ) echo 'selected = "selected"'; ?>>FR</option>
<option value="1" <?php if (!empty($region) && $region == '1') echo 'selected = "selected"'; ?>>بن عروس</option>
<option value="2" <?php if (!empty($region) && $region == '2') echo 'selected = "selected"'; ?>>زغوان</option>
<option value="3" <?php if (!empty($region) && $region == '3') echo 'selected = "selected"'; ?>>تونس</option>
</select>
</td>
</tr>
<tr>
<td align="center">المهام</td>
<td align="center">
<select id="role" name="role">
<option value="0"></option>
<option></option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td align="center">العملية</td>
<td align="center">
<?php
$fonki = mysql_query("SELECT * FROM fonctions")
or die(mysql_error());
// get results from database
$operage = mysql_query("SELECT t.* , o.* FROM taches_redaction t,operations o WHERE t.operation=o.oper_id GROUP BY operation")
or die(mysql_error());
// display data in table
/* echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>"; */
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_assoc( $operage )) {
if($row['oper_id'] == $operation)
{ // echo out the contents of each row into a table
echo '' . $row['operation_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<?php
echo "<td>
<select name=operation>
<option value =0></option>";
include "../render/render_operation-selected.php";
echo "</select>
</td>";
?>
</tr>
<tr>
<td>تاريخ التحيين</td>
<td>
<?php
echo '' . $row['date'] . '';
?>
</td>
<td style="direction:rtl;">
<?php echo "<input type='text' value='".date('o/m/d')."' style='width: 148px;' name='date' readonly=readonly>";?>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="تغيير" class="brd"></td>
<td align="center">
<input type="submit" value="إلغاء" onClick="history.go(-1);return true;" class="bbl">
</td>
</tr>
</table>
<?php
}
// connect to the database
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['serie']))
{
// get form data, making sure it is valid
$serie = $_POST['serie'];
$user_id = mysql_real_escape_string(htmlspecialchars($_POST['user_id']));
$journee = mysql_real_escape_string(htmlspecialchars($_POST['journee']));
$titre = mysql_real_escape_string(htmlspecialchars($_POST['titre']));
$region = mysql_real_escape_string(htmlspecialchars($_POST['region']));
$role = mysql_real_escape_string(htmlspecialchars($_POST['role']));
$operation = mysql_real_escape_string(htmlspecialchars($_POST['operation']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
// check that firstname/lastname fields are both filled in
if ($user_id == '' || $journee == '' || $titre == '' || $region == '' || $role == '' || $operation =='' || $date =='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($serie, $user_id, $journee, $titre, $region, $role , $operation, $date, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE taches_redaction SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date' WHERE serie='$serie'")
/* frere update */
/*
AND
mysql_query("INSERT copie SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT colla SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT archive SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
*/
or die(mysql_error());
// once saved, redirect back to the view page
/* header('Refresh: 2; URL = taches_view.php');
*/
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['serie']) && is_numeric($_GET['serie']) && $_GET['serie'] > 0)
{
// query db
$serie = $_GET['serie'];
$result = mysql_query("SELECT * FROM taches_redaction WHERE serie=$serie")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$serie = $row['serie'];
$user_id = $row['user_id'];
$journee = $row['journee'];
$titre = $row['titre'];
$region = $row['region'];
$role = $row['role'];
$operation = $row['operation'];
$date = $row['date'];
// show form
renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
<!-- end .content --></div>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<?php
include '../theme/footer-global.php';
?>

form submit not working

I have a table that prints out all available cameras. It uses a form to change these settings. The problem is that the form only updates the last camera in the entry. In other words if I change the form and hit "Apply" for the last camera in the list it will work. If I change the form for any other camera in this list it changes the one to have the same settings as the last camera in the list. There are no issues with any values as far as I can tell.
Sorry for the long dump here, but without being able to narrow down the problem I thought I should include the bulk of it:
// Dont allow direct linking
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
//get current user
$user =& JFactory::getUser();
// get a reference to the database
$db = &JFactory::getDBO();
$query_camera_name = "SELECT camera_id, camera_name, camera_status, camera_quality, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
if (isset($_POST['apply_changes'])) {
//process changes to camera options
$camera_id = $_POST['camera_id'];
$camera_status = check_input($_POST['camera_status']);
$camera_name = check_input($_POST['camera_name'], "You entered an empty camera name. Enter another name and apply changes.");
$camera_quality = check_input($_POST['camera_quality']);
$query_insert_camera = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'", `camera_name` ="'.$camera_name.'", `camera_quality` ="'.$camera_quality.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_insert_camera);
$db->query();
header("location: " . $_SERVER['REQUEST_URI']);
}
echo "<html>";
echo "<head>";
<link href="dashboard/webcam_widget.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function oncameraSubmit(camera_id)
{
document.active_cameras.camera_id.value = camera_id;
return confirm('Apply changes?');
}
</script>
<?php
echo "</head>";
echo "<body>";
if (!isset($result_cameras))
{
//TODO
}
else
{
if ($num_rows == 0)
{
echo '<b><i><center>You currently have no cameras setup. Add a Camera below.</center></i></b>';
}
else
{
?>
<form name="active_cameras" action="<?php htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="hidden" name="camera_id" value="" />
<table id="webcam-table">
<thead>
<tr>
<th>Camera Type</th>
<th>Name</th>
<th>Quality</th>
<th>Status</th>
<th>Camera Actions</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_rows;$i++)
{
//camera_status
if ($result_cameras[$i]["camera_status"] == "ENABLED")
{
$enabled_option = "value='ENABLED' selected='selected'";
$disabled_option = "value='DISABLED'";
}
else
{
$enabled_option = "value='ENABLED'";
$disabled_option = "value='DISABLED' selected='selected'";
}
//camera_quality
if ($result_cameras[$i]["camera_quality"] == "HIGH")
{
$high_option = "value='HIGH' selected='selected'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MEDIUM")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM' selected='selected'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MOBILE")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE' selected='selected'";
}
else
{
//TODO proper logging
}
//camera_type
if ($result_cameras[$i]["camera_type"] == "WEBCAM")
{
$webcam = "value='WEBCAM' selected='selected'";
$axis = "value='AXIS'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "AXIS")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS' selected='selected'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "IPCAM")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS'";
$other = "value='IPCAM' selected='selected'";
}
else
{
//TODO
}
?>
<tr>
<td>
<select name="camera_type">
<option <?php echo $webcam; ?>>Webcam</option>
<option <?php echo $axis; ?>>AXIS</option>
<option <?php echo $other; ?>>Other</option>
</select>
</td>
<td>
<input type="text" size="32" maxlength="64" name="camera_name" value="<?php echo $result_cameras[$i]["camera_name"]; ?>" />
</td>
<td>
<select name="camera_quality">
<option <?php echo $high_option; ?>>High</option>
<option <?php echo $medium_option; ?>>Medium</option>
<option <?php echo $mobile_option; ?>>Mobile</option>
</select>
</td>
<td>
<select name="camera_status">
<option <?php echo $enabled_option; ?>>Enabled</option>
<option <?php echo $disabled_option; ?>>Disabled</option>
</select>
</td>
<td>
<input type="submit" name="apply_changes" value="Apply" onClick="javascript:return oncameraSubmit(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/>
</td>
</tr>
<?php
}
echo "</tbody>";
echo "</table>";
echo "</form>";
}
}
It looks like you have multiple HTML elements with the same name. As such, you want to get back an array of values when the form is posted.
As such, Get $_POST from multiple checkboxes looks like it might be helpful.
Alternatively, extend oncameraSubmit so that it stores all the data in a hidden input field (not just the id). Then when you update the database, use these hidden fields.
Your form element names are clashing. When you define a form element e.g. 'camera_status' twice, you will only receive the last value in the POST.
Use form array notation, e.g.: "camera_status[]" or even better "camera_status[$id]". Then your PHP code will recieve arrays as POST data and you will be able to update everything at once.

Categories