form submit not working - php

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.

Related

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;
};
?>

Trying to use PHP to send two variables to SQL query

I'm sorry for such a basic question but I'm a bit stumped. I've been trying to build a basic website for a database I created that will graph the data. There are two variable lists that the user selects from and the data from this then is supposed to generate the requested information. However, I'm completely lost as to how to get the data selected from the list to appear in the results page. It will search under the 'country' variable, but not goods. I know that I'm probably doing something stupid, but I'm not sure what it is.
The code I'm using for the dropdown menus on the forms is as follows:
<form id="Country" name="Country" method="get" form action="/database/results_page.php"><table border="1">
<tr>
<td width="68">Name</td>
<td width="48"><span id="sprytextfield4">
<select name="selcountry" id="selcountry" title="<?php echo $row_rsCountrydropdown['']; ?>">
<?php
do {
?>
<option value="<?php echo $row_rsCountrydropdown['country']?>" <?php if($varcountry_rsexportsearch == $row_rsCountrydropdown['country']){echo 'selected';}?>><?php echo $row_rsCountrydropdown['country']?></option>
<?php
} while ($row_rsCountrydropdown = mysql_fetch_assoc($rsCountrydropdown));
$rows = mysql_num_rows($rsCountrydropdown);
if($rows > 0) {
mysql_data_seek($rsCountrydropdown, 0);
$row_rsCountrydropdown = mysql_fetch_assoc($rsCountrydropdown);
}
?>
</select>
<select name="selgoods" id="selgoods" title="<?php echo $row_rsGoodsdropdown['']; ?>">
<?php
do {
?>
<option value="<?php echo $row_rsGoodsdropdown['name']?>" <?php if($vargoods_rsexportsearch == $row_rsGoodsdropdown['name']){echo 'selected';}?>><?php echo $row_rsGoodsdropdown['name']?></option>
<?php
} while ($row_rsGoodsdropdown = mysql_fetch_assoc($rsGoodsdropdown));
$rows = mysql_num_rows($rsGoodsdropdown);
if($rows > 0) {
mysql_data_seek($rsGoodsdropdown, 0);
$row_rsGoodsdropdown = mysql_fetch_assoc($rsGoodsdropdown);
}
?>
</select>
</tr>
</table>
<input type="submit" name="submit" id="submit" value="Submit" onChange="row_rsCountrydropdown.submit()" />
</form>
and my SQL for the results page is as follows:
mysql_select_db($database_cork_normalised, $cork_normalised);
$query_query = "SELECT exports.trade_year, country_id.country, goods.name, exports.Cork FROM country_id, goods, exports WHERE country_id.country_id='varcountry' and goods.goods_id='vargoods'";
$query = mysql_query($query_query, $cork_normalised) or die(mysql_error());
$row_query = mysql_fetch_assoc($query);
$maxRows_query = 10;
$pageNum_query = 0;
if (isset($_GET['pageNum_query'])) {
$pageNum_query = $_GET['pageNum_query'];
}
$startRow_query = $pageNum_query * $maxRows_query;
$vargoods_query = "-1";
if (isset($_POST['selgoods'])) {
$vargoods_query = $_POST['selgoods'];
}
$varcountry_query = "-1";
if (isset($_POST['selcountry'])) {
$varcountry_query = $_POST['selcountry'];
}
If anyone could help I'd be really grateful, this is my first foray into PHP and I'm a bit lost in it.

Programmatically generating a drop-down menu

I have a drop down menu below:
$form = "
<form action='" . htmlentities($_SERVER["PHP_SELF"]) . "' method='post'>
<table>
<tr>
<td><select name='year' id='yearDrop'>
<option value=''></option>
<option value='$getyear[1]'>1</option>
<option value='$getyear[2]'>2</option>
<option value='$getyear[3]'>3</option>
<option value='$getyear[4]'>4</option>
<option value='$getyear[5]'>5</option>
<option value='$getyear[6]'>6</option>
<option value='$getyear[7]'>7</option>
<option value='$getyear[8]'>8</option>
<option value='$getyear[9]'>9</option>
<option value='$getyear[10]'>10</option>
</select></td>
</tr>
</table>
</form>
";
Notice the drop down menus are in a php varaible in a form. My question is: "is there a much better and shorter method of displaying the drop down menu above?". Maybe by using some sort of loop to loop through each value and give each option the same value attribute?
I want to use getyear in order to fit in a simple if statement:
if ($getyear){
echo "year is chosen";
}else{
$errormsg = "You must enter in Student's current Academic Year to Register";
}
UPDATE:
<?php
$getyear = (isset($_POST['year'])) ? $_POST['year'] : '';
$errormsg = (isset($errormsg)) ? $errormsg : '';
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$yearHTML = '';
$yearHTML .= '<select name="year" id="yearDrop">'.PHP_EOL;
$yearHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($years as $year) {
$yearHTML .= "<option>$year</option>".PHP_EOL; // if no value attribute, value will be whatever is inside option tag, in this case, $year
}
$yearHTML .= '</select>';
if( (isset($_POST['registerbtn']))){
$getyear = $_POST['year'];
if (!in_array($getyear , $years)){
echo "year is chosen";
}else{
$errormsg = "You must enter in Student's current Academic Year to Register";
}
}
$form = "
<form action='" . htmlentities($_SERVER["PHP_SELF"]) . "' method='post'>
<table>
<tr>
<td></td>
<td id='errormsg'>$errormsg</td>
</tr>
<tr>
<td>Year:</td>
<td>{$yearHTML}</td>
<td><input type='text' name='year' value='$getyear' /></td>
</tr>
<tr>
<td></td>
<td><input type='submit' value='Register' name='registerbtn' /></td>
</tr>
</table>
</form>";
echo $form;
?>
The foreach loop is extremely beneficial when looping over arrays and performing operations on their values.
foreach control structure
<?php
// reference values for output and for validation later
$min_year = 1900; // using as an example
$max_year = 2012;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
// for HTML output
if (empty($_POST)) { // display form
$html = '';
foreach ($years as $year) {
$html .= "<option>$year</option>"; // if no value attribute, value will be whatever is inside option tag, in this case, $year
}
// output HTML
echo $html;
} else { // process form
$chosen_year = isset($_POST['year']) ? $_POST['year'] : "";
if (!in_array($chosen_year , $years) { // year is invalid
$errormsg = "You must enter in Student's current Academic Year to Register";
} else { // year is chosen
echo 'year is chosen';
}
}
This file will generate the select options automatically, and give you an easy place to do further processing.
function process_form(){
if(!isset($_POST['year']) || !is_numeric($_POST['year'])){
// Form invalid
return false;
}
$year = $_POST['year'];
// Perform actions - save to database, etc..?
// Form valid
return true;
}
$error = false;
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Form submitted
$result = process_form();
if($result){
?>
<p>Valid year selected</p>
<?php
exit;
}
$error = true;
}
?>
<form action="" method="post">
<?php if($error){ ?>
<p class="error">You must select the student's current academic year to register</p>
<?php } ?>
<label for="select_year">Academic Year:</label>
<select name="year" id="select_year">
<option value=""></option>
<?php for($year = $start_year; $year <= $end_year; $year++){ ?>
<option value="<?php echo $year;?>"><?php echo $year;?></option>
<?php } ?>
</select>
<button type="submit">Register</button>
</form>

PHP AJAX form not posting to PHP

A form contains a dropdown menu on change it should fetch the value from the database using ajax and dislay the checkbox with .
uptil here its wking good,when i submit form the checkbox values is not getting posted.
<form name="test" >
<tr>
<td align="left"><b>System :</b> </td>
<td align="left">
<select name="system" size="1" onchange="regionsa(this.value);" >
<option value="0">Select a System</option>
<?php // Retrieve all the announcement types and add to the pull-down menu.
$q = "SELECT * FROM System";
$r = mysqli_query ($CARE_dbc, $q);
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
// $sys_name = $edit_menu['system'];
?>
<option value="<? echo $row[1];?>" <? if($row[1]==$edit_menu['system'])
{
echo $selec = "selected";
}?> >
<? echo $row[1];?>
</option>
<? }?>
</select>
</td>
</tr>
<tr>
<td align="left">
<b>User Type :</b> </td>
<td align="left" ><span id="sant">
<?php // Retrieve all the announcement types and add to the pull-down menu.
$qUTdd = "SELECT * FROM `UserType`";
$rUTdd = #mysqli_query ($CARE_dbc, $qUTdd);
while ($rUTddrow = mysqli_fetch_assoc($rUTdd))
{
$utype_qr = mysqli_query($CARE_dbc,"SELECT * FROM `menu_users` WHERE `menu_users`.menu_id='".$_REQUEST['id']."'");
//$ut = mysqli_fetch_assoc($utype_qr);
?>
<input type="checkbox" name="user_type[]" value="<? echo $rUTddrow['idUType'];?>" <? while($ut = mysqli_fetch_assoc($utype_qr))
{
if($ut['user_type']==$rUTddrow['idUType'])
{
echo "checked";
}
}?> /> <?echo "<b>".$rUTddrow['userType']."</b>"; ?>
<?
}
?>
</span>
</td>
</tr>
<input type="submit" name="submit" value="Add" />
<input type="hidden" name="submitted" value="TRUE" />
</form >
<script language="javascript">
var http = createRequestObject();
function createRequestObject()
{
var request_o; //declare the variable to hold the object.
var browser = navigator.appName; //find the browser name
if(browser == "Microsoft Internet Explorer"){
/* Create the object using MSIE's method */
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
/* Create the object using other browser's method */
request_o = new XMLHttpRequest();
}
return request_o; //return the object
}
function regionsa(stateid)
{
//alert(stateid);
http.open('get','internal_request.php?id='+stateid);
http.onreadystatechange = handleresponse;
http.send(null);
}
function handleresponse()
{
if(http.readyState == 4)
{
var response = http.responseText;
//alert(response);
document.getElementById('sant').innerHTML = response;
}
}
</script>
Internal_request.php
<?php
if($_REQUEST['id']=='annmet' && isset($_REQUEST['id']) && !empty($_REQUEST['id']))
{
$qUTdd = "SELECT * FROM annmet.`usertype`";
$rUTdd = #mysqli_query ($CARE_dbc, $qUTdd);
while ($rUTddrow = mysqli_fetch_assoc($rUTdd))
{
$utype_qr = mysqli_query($CARE_dbc,"SELECT * FROM CARE.`menu_users` WHERE CARE.`menu_users`.menu_id='".$_REQUEST['id']."'");
//$ut = mysqli_fetch_assoc($utype_qr);
?>
<input type="checkbox" name="user_type1[]" value="<? echo $rUTddrow['idUType'];?>"
<? while($ut = mysqli_fetch_assoc($utype_qr))
{
if($ut['user_type']==$rUTddrow['idUType'])
{
echo "checked";
}
}?> /> <?echo "<b>".$rUTddrow['UserT']."</b>"; ?>
<?
}
}
?>
name of the AJAX generated checkboxes is user_type*1*[] while original checkbox name is user_type[].
EDIT:
You have not mentioned a value for "method" attribute of Form element. Therefore this form uses default form submission method which is GET. Therefore you don't get any data for $_POST variable. Print $_GET variable using print_r and check.

how do you use multiple dropdowns and know which status each has?

the below code shows a table with users to be accepted or declined. the code as it is has a dropdown on the end allowing to either accept it, deny it or leave as is. there is a button on the bottom to submit the form and after that there should be a php script that decides which user is accepted, denied or still pending.
what would be the best approach to make this work since i find it hard to link the dropdown box and the id.
<table align='center' width='90%'>
<tr>
<center><td><strong>ID:</strong></td></center>
<center><td><strong>Name:</strong></td></center>
<center><td><strong>Level:</strong></td></center>
<center><td><strong>Job:</strong></td></center>
<center><td><strong>Guild:</strong></td></center>
<center><td><strong>Date:</strong></td></center>
<center><td><strong>Action:</strong></td></center>
</tr>
<?php
$id = 0;
$result=mysql_query("SELECT * FROM accounts WHERE active ='0' ORDER BY date LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$id = $id + 1;
?>
<form method='POST' action=''>
<tr>
<center><td><?php echo $row['id']; ?></td></center>
<center><td><?php echo $row['user']; ?></td></center>
<center><td><?php echo $row['level']; ?></td></center>
<center><td><?php echo $row['job']; ?></td></center>
<center><td><?php echo $row['guild']; ?></td></center>
<center><td><?php echo $row['date']; ?></td></center>
<td>
<select name='action_<?php echo $row['id']; ?>'>
<option value='none'>None</option>
<option value='accept'>Accept</option>
<option value='decline'>Decline</option>
</select>
</td>
</tr>
<?php } ?>
<tr>
<br /><td align='right'><input type='submit' value='Submit' name='submit' /></td>
</tr>
</form>
</table>
<?php
if(isset($_POST['submit'])) {
if(isset($_POST['action_'.$row['id'].'']) && $_POST['action_'.$row['id'].''] == "accept" ) {
$acc = mysql_query("UPDATE `accounts` SET `active`='1' WHERE `id` = '".$row['id']."'");
echo "<meta http-equiv=refresh content=\"5; url=?wesofly=main&page=recruitment\">";
}elseif(isset($_POST['action_'.$row['id'].'']) && $_POST['action_'.$row['id'].''] == "decline" ) {
$dec = mysql_query("DELETE * from `accounts` WHERE '".$row['id']."'");
echo "<meta http-equiv=refresh content=\"0; url=?wesofly=main&page=recruitment\">";
}
}
?>
Your code is confusing. Your WHILE loop starts before the form tag, but the WHILE loop closes before the form tag closes. This means that you are going to have multiple form elements.
So, first of all, change that in your code. Next the way you want this to work is using arrays.
Your drop down box should look like this
<select name='action[<?php echo $row['id']; ?>]'>
<option value='none'>None</option>
<option value='accept'>Accept</option>
<option value='decline'>Decline</option>
</select>
Then on the PHP side, you should be able to do something like
foreach ($_REQUEST['action'] as $key => $value) {
$id = $key;
$status = $value;
// put your code here to update the specific database item
}
I think you'll be better off with HTML form arrays, for instance:
<select name="action[<?php echo $row['id']; ?>]">
<option value="none">None</option>
<option value="accept">Accept</option>
<option value="decline">Decline</option>
</select>
And inside your php code, you would simply loop through the submitted action field in your $_POST array to find which id had which action. Each entry would be presented as an array, the key would be the user's id.

Categories