I have some data in a html table which has been populated from a mysql database. To put the data into the html table I have done the following:
$meterdetail = getMeterDetails($ticketNumber);
This gets a number of records from the mysql table Then for each record retrieved from the db I do the following..
foreach ($meterdetail as $v2) {
<tr>
<td class='tableText'>
<input type='hidden' name='ids[]' value='".$v2['id']."'>
<input type='text' name='meters[]' value=''>
</td>
</tr>
Ultimately what I am trying to do here is update each record (based on the ID from the mysql table) with the values in the input of the table.
When I click on a submit button I need to step through each record that was collected and insert the value that was typed into the html form corresponding to the relevant id.
To process the $_POST data I do the following
if (!empty($_POST['meters']) && !empty($_POST['ids'])) {
for ($i = 0; $i < count($_POST['meters']); $i++) {
updateRecord($_POST['ids'][$i],$_POST['meters'][$i]);
}
}
This seems to be working but for some reason I don't feel comfortable with this solution so my question is: Is there a better (more elegant / more correct) way to do this (particularly the processing of the 2 $_POST arrays)? Can I create one associative array with the ID as key and the form input value as the corresponding value?
$met = $_POST['meters'];
$id = $_POST['ids'];
if (isset($met) && isset($id))
{
for ($i = 0; $i < count($id); $i++)
{
updateRecord($id[$i],$met[$i]);
}
}
A better way is to make sure you have 'set in stone' names for your inputs;
foreach ($meterdetail as $key => $v2) {
echo "
<tr>
<td class='tableText'>
<input type='hidden' name='id_".$key."' value='".$v2['id']."'>
<input type='text' name='meter_".$key."' value=''>
</td>
</tr>
";
}
And than process the post-data as such:
$ids = array();
$meters = array();
foreach($_POST as $name => $value) {
if(strpos($name, 'id_') === 0) {
$ids[substr($name, 3)] = $value;
}
if(strpos($name, 'meter_') === 0) {
$ids[substr($name, 3)] = $value;
}
}
if(count($ids) && count($meters)) {
foreach($ids as $key => $id) {
updateRecord($id, $meters[$key]);
}
}
This way you are always sure you have accompanying values which you are updating in the db.
PS: this is proof of concept... haven't tested it yet...
Related
I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
I have this php statement that collects data from a database table. It loops over all rows and separates them into tables of 2 (home team and away team for that game). I also have radio buttons so the user can pick which team they would like to win for each game. There are 9 games.
$games = array();
for($num = 1; $num <= 9; $num++)
{
$games[$num] = "<table border='1'><tr><b><h4>Game ".$num."</h4></b><th>Home</th><th>Draw</th><th>Away</th></tr>";
}
while ($row = mysql_fetch_array($rs))
{
for($num = 1; $num <= 9; $num++)
{
$games[$num] .=
" <tr>
<td><input type='radio' id='home".$num."' name='game".$num."' value='".$row['home'.$num]."' > ".$row['home'.$num]."</td>
<td>Draw <br /><input type='radio' id='draw".$num."' name='game".$num."' value='0'></td>
<td>".$row['away'.$num]."<input type='radio' id='away".$num."' name='game".$num."' value='".$row['away'.$num]."'></td>
</tr>";
}
}
On submit, i want to be able to do something for each game via SELFSUBMIT.
So if a user selects home team for game n, i want to display a message.
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST['game".$num."'] = ('home'.$num))
{
echo ('home'.$num);
}
}
Thats my wrong php code. Please tell me if i can workaround this.
You might want to use jquery
$(document).ready( function(){
$("input[id^=home]").on("click", function(){
$("#spanDisplay").html( $(this).attr("id") );
//you can also display $(this).attr("name") or $(this).val() to print the value
});
});
In your html, you can use span or div to display the value of id for example.
So in your span
<span id="spanDisplay"></span>
UPDATE: using PHP only
$games[$num] .= "<form name="aForm" method="POST" action="afterSubmit.php">";
for($num = 1; $num <= 9; $num++){
$games[$num] .= "<tr><td><input type='radio' id='home".$num."' name='game".$num."' value='".$row['home'.$num]."'> ".$row['home'.$num]."</td>
<td>Draw <br /><input type='radio' id='draw".$num."' name='game".$num."' value='0'></td>
<td>".$row['away'.$num]."<input type='radio' id='away".$num."' name='game".$num."' value='".$row['away'.$num]."'></td></tr>";
}
$games[$num] .= "</form>";
You will need to surround your input with the form tag, submit and post it to the next page for instance afterSubmit.php. So in afterSubmit.php page, you can put something like this:
for($num = 1; $num <= 9; $num++){
if( isset( $_POST['game".$num."'] ) ){
echo $_POST['game".$num."']; //echo the value
}
}
How to declare variables in the array using for loop. I have 3 input fields on my page, so when the submit buttons is pressed, it should process the following line of code. On my html page, there are fields named: question1, question2, and question3.
Here's the code of process.php file. It doesn't work for some reason, I suppose there are several mistakes here but I cannot find em.
<?php
$question = array();
for($j=1; $j<4; $j++) {
$question[j] = $_POST['question[j]'];
$result;
$n=1;
if($question[j] != "") {
$result = $n.'): '.$question[j].'<br/><br/>';
$n++;
}
}
echo $result;
?>
<?php
$question = array();
$result = "";
for($j=1; $j<4; j++) {
$question[$j] = $_POST["question$j"];
if($question[$j] != "") {
$result .= $j.'): '.htmlentities($question[$j]).'<br/><br/>';
}
}
echo $result;
?>
Though you don't need an array.
<?php
$result = "";
for($j=1; $j<4; j++) {
$result .= $_POST["question$j"]!="" ? htmlentities($_POST["question$j"]).'<br/><br/>':'';
}
echo $result;
?>
For starters, arrays are zero-indexed, so I think you want this:
for($j=0; $j<3; j++)
Aside form that, this doesn't evaluate the value of j:
$_POST['question[j]']
I think you might want something like this:
$_POST["question$j"]
However, if you made the indexing change above, since your elements are named starting with 1 instead of 0 then you'd need to account for that:
$_POST['question' . $j+1]
You can use following HTML code
<input type="text" name="question[a]" />
<input type="text" name="question[b]" />
<input type="text" name="question[c]" />
with following PHP code:
foreach($_POST["question"] as $key => $value)
{
// $key == "a", "b" or "c"
// $value == field values
}
Remember to sanitize Your input!
I created a PHP function that will create a form for any table that you have in a database. This function allows you to specify the name of the table and a list of all the columns you want in your html form. Everything works great, if the user puts something in for the text inputs. If they don't, then strange things happen when trying to retrieve the column name. Please see the function below...
function generateSubmissionFromTable($db, $tablename, $rowstoinclude,$action)
{
$query = 'SHOW COLUMNS from '.$tablename;
$colsresult = mysql_query($query,$db);
$table = array();
while($row = mysql_fetch_array($colsresult))
{
array_push($table,$row[0]);
}
$finalcolumns = array();
foreach($table as $row)
{
foreach($rowstoinclude as $inc)
{
if($row == $inc)
{
array_push($finalcolumns,$row);
}
}
}
echo '<form name="loginy" method="post" action="'.$action.'">';
foreach($finalcolumns as $column)
{
echo 'Please enter the '.$column.'<br/>';
echo '<input type=text name=column['.$column.'] value="blah"/><br/>';
}
echo '<input type="hidden" name="tablename" value="'.$tablename.'" />';
echo '<button type="button" size="4" style="font-size:35px;" onClick="document.loginy.submit()">Submit</button>';
echo '</form>';
}
Now, comes the weird part... I have another function that will generate the query statement based off that automatic form generation.
function submitDataToTable($post)
{
$query = 'INSERT INTO '.$post['tablename'].'(';
$buf = "";
while($col = current($post['column']))
{
$query = $query.$buf.key($post['column']);
$buf=",";
next($post['column']);
}
$buf = "";
$query = $query.') VALUES (';
foreach($post['column'] as $val)
{
$query = $query.$buf.$val;
$buf = ",";
}
$query = $query.')';
echo 'QUERY='.$query;
}
Now for example I have a table that I want to input for 3 columns (name, link, descritpion) and I fill in the top 2 and not the bottom, the query gets generated as this...
QUERY=INSERT INTO LinksWebsites(name,link) VALUES (blah,blah,)
which as you can see, the query is missing the column (name,link,descritption) but what is weird if you take a look at the post...
POST =Array ( [column] => Array ( [name] => blah [link] => blah [description] => ) [tablename] => LinksWebsites )
which shows all the keys, but my PHP method of extracting the keys is not showing all the keys! (Might have something to do with the current($array) and key($array) calls?)
Try putting a java script in your html where you will put the php function that text inputs must not be blank before trying to submit it.
<script>
function validateForm()
{
if (inputbox==null || inputbox=="")
{alert("Input should not be empty");
return false;
}
}
</script>
Just include the onsubmit="return validateForm()" in the form tag.
I have checkboxes which is generated in while loop. These checkboxes are always checked for the first time and the value stored in the database is "On". But when user unchecks it, I want to store "Off" in database. But my problem is i am not able to access the checkbox name to check if which checkboxes are unchecked on button click. I wrote this code
while($row = mysql_fetch_assoc($result)) {
if($pck_id_renew == 'On')
{
echo '<td class=c><input type="checkbox" id="renew_chk" name="renew_chk"
checked="checked" style="width:50px" value="On"/></td>';
}
if($pck_id_renew == 'Off') {
echo '<td class=c><input type="checkbox" id="renew_chk" name="renew_chk"
style="width:50px" value="Off"/></td>';
}
}
You will only receive the input value of checkboxes that are checked. Use an array and store all available checkbox names in it. Loop through this array to detect which checkboxes are checked/unchecked.
Code may look something like this:
// Define available checkboxes
$inputs = array('renew_chk', ...);
// Check input values
$values = array();
foreach ($inputs as $input) {
if (isset($_POST[$input])) {
$values[$input] = 'On';
}
else {
$values[$input] = 'Off';
}
}
// Loop through $values and store value in database
foreach ($values as $input => $value) {
// UPDATE database SET $input = $value WHERE id = [n];
}