how to push data from html grid to mysql? - php

I am trying to push the data from this simple html grid into sql but I can't do it. in the beginning, I got the error that there was no index for the var impressions. I fixed that. when I use just the advertiser value I can push the data into mysql while with the second value, I can't succeed. can you explain me what I am doing wrong?
Thanks in advance
<?php
include_once 'con_ui.php';
if(isset($_POST['btn-save']))
{
$advertiser = $_POST["advertiser"];
$impressions = (isset($POST["impressions"])?
$_POST["impressions"]:'');
$sql_query = "INSERT INTO data(adv, imp) VALUES('$advertiser', '$impressions')";
mysql_query($sql_query);
// sql query for inserting data into database
}
?>
<html>
<head>
</head>
<body>
<form method="post">
<table id="myTable" align='center' cellspacing=0 cellpadding=5 border=1>
<tr>
<th>advertiser</th>
<th>impressions</th>
</tr>
<td>
<select name="advertiser" id="advertiser">
<option value="">Select advertiser</option>
<option value = "Brita ">Brita</option>
<option value = "Sammontana">Sammontana</option>
</select>
</td>
<td name= "impressions" id="impressions" >1000000</td>
<td>
<button type="submit" name="btn-save"><strong>SAVE</strong></button>
</td>
</form>
</body>
</html>

There's a few things wrong here:
Firstly the $POST in
$impressions = (isset($POST["impressions"])?$_POST["impressions"]:'');
Is missing an underscore and should be a $_POST
$impressions = (isset($_POST["impressions"])?$_POST["impressions"]:'');
Secondly the browser won't recognize
<td name= "impressions" id="impressions" >1000000</td>
as a form field. If you want to pass on values that the user can't edit you have a few options. You can use a hidden field like:
<td><input type="hidden" name="impressions" id="impressions" value="1000000">1000000</td>
or you can use a text input and disable user input like
<td><input type="text" name="impressions" id="impressions" value="1000000" disabled></td>

here you have the details of the code that i am using to achieve for adding the raws automatically, have the users entering data and keeping the code editable
Hey thanks for your reply. Problem being is i need to have the user enter the date into the cell and and have and the content should be editable. in addition i'm having a button add row, to insert a new raw but doesn't work if use the form type as input. here you have the full code
<?php
include_once 'con_ui.php';
if(isset($_POST['btn-save']))
{
// variables for input data
$advertiser = $_POST["advertiser"];
$impressions = (isset($_POST["impressions"])?
$_POST["impressions"]:'');
// variables for input data
// sql query for inserting data into database
$sql_query = "INSERT INTO data(adv, imp) VALUES('$advertiser', '$impressions')";
mysql_query($sql_query);
// sql query for inserting data into database
}
?>
<html>
<head>
<script>
function myFunction() {
var table = document.getElementById("myTable");
var new_client = document.getElementById("advertiser_row1").innerHTML;
var new_impressions = document.getElementById("impressions_row1").innerHTML;
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
}
</script>
</head>
<body>
<table id="myTable" align='center' cellspacing=0 cellpadding=5 border=1>
<form method="post">
<tr>
<th>advertiser</th>
<th>impressions</th>
</tr>
<td>
<select name="advertiser" id="advertiser_row1">
<option value="">Select advertiser</option>
<option value = "Brita ">Brita</option>
<option value = "Sammontana">Sammontana</option>
</select>
</td>
<td><input type="text" name="impressions" id="impressions_row1" value="1000000"></td>
<td>
<button onclick="myFunction()">Add Row</button>
</td>
<td>
<button type="submit" name="btn-save">Save</button>
</td>
</tr>
</form>
</table>
</body>
</html>

Related

PHP - HTML best practices to handle (submit) generated rows

I have html table generated via ajax. And last column on this table contains button. My question is what is the best practice to submit these rows (only one at time. I need use this method to amend records).
Is it worth to wrap each row with
<form>
<input type="hidden" value="hidden value">
<input type="submit">
</form>
Or people using something difference? Reason why i'm asking for is because i'm worry about very long list example 1k rows or 10k rows (that means i will have 1k or 10k forms on a page).
You can just use a hyperlink (which you can style to look like a button using CSS if you want). e.g:
Edit
where the value you give as the "id" parameter is the primary key of the record in that row.
Then in edit.php look for the id value using $_GET["id"] and fetch the appropriate record from the DB.
As Progrock advises, a form element may only be used "where flow content is expected" (i.e. not as a direct child of table or tr).
HTML 5 introduces a form attribute as a workaround:
<form id="row_1">
<input type="hidden" name="id" value="pk1">
</form>
<form id="row_2">
<input type="hidden" name="id" value="pk2">
</form>
<table>
<tr>
<td> <input type="text" name="attribute1" form="row_1"> </td>
<td> <input type="submit" form="row_1"> </td>
</tr>
<!-- and so on for each row -->
</table>
It has been brought to my attention that in this case, there is no direct user input being submitted, but only generated contents.
Well, then the solution is even simpler:
<table>
<tr> <td>
<form id="row_1">
<input type="hidden" name="id" value="pk1">
<input type="hidden" name="attribute1" value="whatever">
<input type="submit">
</form>
</td> </tr>
<!-- and so on for each row -->
</table>
I thought I'd have a go without form elements, working with editable table cells. Within each row you provide a button. And when you click it, an ajax post is made of the cell values.
You could have a non js fall back where the save button is replaced for an edit button that takes you to another page with a single form.
Forgive my JS.
I have the session storage in there just to check the concept.
<?php
session_start();
var_dump($_SESSION);
$data = array(
23 => ['triangle', 'green', '2'],
47 => ['square', 'red', '3'],
17 => ['pentagon', 'pink', '4']
);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Save state here
$_SESSION['submission'] = $_POST;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
$('button').click(function() {
// Get all table cells in the buttons row
var $cells = $(this).closest('tr').find('td[contenteditable="true"]');
var jsonData = {};
$.each($cells, function() {
jsonData[get_table_cell_column_class($(this))] = $(this).text().trim();
});
jsonData['id'] = $(this).attr('id');
$.post('',jsonData, function() {
alert('Saved.');
});
});
function get_table_cell_column_class($td)
{
var $th = $td.closest('table').find('th').eq($td.index());
return $th.attr('class');
}
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th class="shape">Shape</th>
<th class="colour">Colour</th>
<th class="width">Width</th>
<th>Ops</th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key => $row) { ?>
<tr>
<?php foreach($row as $field) { ?>
<td contenteditable=true>
<?php echo $field ?>
</td>
<?php } ?>
<td>
<button id="<?php echo $key ?>">Save</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
You can use the following
<table id="YourTableId">
...
<tr data-id="yourrowId">
<td class="col1"> value1</td>
<td class="col2"> value2</td>
<td class="col3"> value3</td>
<td class="actions">
Submit
</td>
</tr>
....
</table>
your javascript code will be like
$(document).ready(function (){
$('#YourTableId a').off('click').on('click',function(e){
e.preventDefault();
var tr = $(this).closest('tr')
var data={ // here you can add as much as you want from variables
'id' : tr.data('id), // if you want to send id value
'col1': tr.find('.col1').text(),
'col2': tr.find('.col2').text(),
'col3': tr.find('.col3').text(),
};
$.ajax({
method: 'post',
url: 'your url goes here',
data: data,
success: function(result){
// handle the result here
}
});
});
});
Hope this will help you

Best practice in adding form row

I have a working form with a javascript 'Add Row' button, data collection and processing by PHP. While it works, the code seems fairly high-maintenance and clumsy to me (for one thing, every time I change the form I need to work the same changes into the js that adds the new row). I'm looking for suggestions to make it more sleek and simple. Currently I'm assigning each input a unique name, with hidden input that keeps track of the number of rows for me, and then I use that number to determine the amount of for loops the PHP script needs to work through to post to the database.
One thing I've considered is changing from input names to using name[], but I'm not sure if that's the right method for my needs, and how I post each row as a separate record to the database. In any case, here's the code.
HTML
<table id="table1">
<tr style="display: none"><td colspan="2">
<input type="hidden" id="samp_count" name="samp_counter" value="" />
<input type="hidden" value="sample" name="type1" /></td>
</tr>
<tr>
<td >pic caption </td>
<td>
<input type="text" name="desc1"/></td></tr>
<tr>
<td >extended description</td>
<td><textarea style="width:100%" rows="7" name="notes1"></textarea></td>
</tr>
<tr>
<td>pic file</td>
<td><input id="pic_file1" type="file" name="pic1" /></td>
</tr>
</table>
<button type="button" class="add_row" width="40px" id="samp_add_button">add row
JavaScript for the button
$(document).ready(function(){
$("#samp_count").val("1");
$("#samp_add_button").click(function(){
var iter_str=$("#samp_count").val();
var pic_id = "#pic_file" + iter_str;
if (!$(pic_id).val()){
$("#samp_error").css("visibility","visible");
}
else{
iter_str ++; // update counter
$("#samp_count").val(iter_str); //reset counter in table header to current count
var a = '<tr><td colspan="2" ><span>pic caption<input type="text" name="desc'+iter_str+'"/></span><br /></td>";
var b = '<td rowspan="3">extended description<br /><textarea style="width:100%" rows="7" name="notes'+iter_str+'"></textarea></td>';
var c = '<tr><td colspan="2" >pic file</td><td><input id="pic_file'+iter_str+'" type="file" name="pic'+iter_str+'" /></td></tr>';
$("#table1").append(a+b+c);
$("#samp_error").css("visibility","hidden");
}
});
});
PHP
<?php
if(isset($_POST['send_button'])&&$isValid==TRUE){
$user = $_POST['user'];
$count_str1 = $_POST['samp_counter'];
$count1 = intval($count_str1);
for ($i=1; $i <= $count1; $i++) {
$desc= "desc".$i;
$pic= "pic".$i;
$notes= "notes".$i;
$desc_con = $_POST[$desc];
$notes_con = $_POST[$notes];
if($_FILES[$pic]["name"]){
if( formFileUpload($pic, $user)){ //custom function to validate and upload pics-- not relevant to question at hand
$uid_path = "portfolios/".$user."/";
$file_path=$uid_path.$_FILES[$pic]["name"];
$dbh = new PDO('mysql:host=localhost;dbname=db', 'admin','pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$statement=$dbh->prepare("INSERT INTO portfolios (UserID, Description, FilePath, FileType, Notes) VALUES (?,?,?,?,?)");
$statement->bindParam(1,$user);
$statement->bindParam(2,$desc_con);
$statement->bindParam(3,$file_path);
$statement->bindParam(4,$_POST[type1]);
$statement->bindParam(5,$notes_con);
$statement->execute();
}
else{
$fileErrorDis="inline";
$isValid=FALSE;
} }}
?>
Link to working website -- self-explanatory but text in Hebrew (in some of the forms, the js has not been updated and the new row does not resemble the original one)

How to get the value in my form

Good Day
my main problem is how can I supply the value in the form to query.
this code gets the id from other table:
if (isset($_GET['machine_no_id']) && is_numeric($_GET['machine_no_id']))
{
$id = $_GET['machine_no_id'];
echo $id;
}
then this code only get the value in form:
if (isset($_GET['submit']))
{
$qty = $_GET['qty'];
echo $qty;
}
enter code here
Assign name to your submit button like <input type="submit" Value="Add" name="submit">.
and in php part,
if(isset($_GET['submit'])){
//insert query
}
and you will get the quantity value by $_GET['add_qty']
and its better if u use the method = 'post' and call the variables using $_POST instead of $_GET
Try this
<input type="submit" Value="Add" name="submit">
if (isset($_GET['submit']))
{
// get id value
$id = $_GET['machine_no_id'];
$qty = $_GET['add_qty'];
}
Try to add submit button in HTML form like,
<input type="submit" Value="Add" name="submit">
And set method to 'POST' in HTML form As it is better to use POST method instead of GET, In PHP code use $_POST to check whether form is submitted or not like,
if($_POST){
// put your PHP code here
}
And Then you can get the quantity value by $_POST['add_qty'];
<html>
<body>
<form action="" method="POST">
<table border="1" cellpadding="5" align="center">
<tr>
<td>ID:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>Quantity:</td>
<td><input type="text" name="add_qty"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" Value="Add"></td>
</tr>
/table>
</form>
</body>
<?php
// connect to the database
include('connect-db.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_REQUEST['submit']))
{
// get id value
$id = $_POST['id'];
$qty = $_POST['add_qty'];
echo $id;
echo $qty;
//mysql_query("UPDATE master_tbl SET qty_left = qty_left + '$qty' WHERE machine_no_id='$id'");
//header("location: show_result.php");
}
?>

subtraction using javascript

The below coding is my doubt. the total fees value is fetched from db. and paid is currently we enter. now i want that if i enter any value in paid, the entered value is subtract from db value and new value is display in bal fees text box and as well as store in db.
my coding is...
<HTML>
<HEAD>
<script language="javascript">
function doMath()
{
var oldbal= parseInt(document.getElementById('totalfees').value);
var paid= parseInt(document.getElementById('paid').value);
var totalfees = oldbal-paid;
document.getElementById('totalfees').value = totalfees;
}
</script>
</HEAD>
<body>
<?php
//fteching query
include("db.php");
$billtype_id = $_GET['billtype_id'];
$result=mysql_query("select * from bill_type where billtype_id=$billtype_id");
while($res=mysql_fetch_array($result))
{
$totalfees=$res['totalfees'];
}
//inserting query
$sql=mysql_query("insert into fees_admin values totalfees='$balfees' WHERE billtype_id='$billtype_id'",$conn);
include("config.php");
$balfees=$_POST['totalfees'];
$sql=mysql_query("insert into fees_admin values totalfees='$balfees' WHERE billtype_id='$billtype_id'",$conn);
?>
//html form
<form name="form" method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<table>
<tr>
<td>Total Fees :</td>
<td><input name="total" type="text" id="oldbal" value="<?php echo $totalfees;?>" readonly="true" style="background-color:#FFFFFF"></td>
</tr>
<tr>
<td>Paid :</td>
<td><input type="text" id="paid" name="paid" onKeyUp="doMath();"></td>
</tr>
<tr>
<td>Bal Fees</td>
<td><input name="totalfees" type="text" id="totalfees" readonly="true" style="background-color:#FFFFFF"></td>
</tr>
</table>
</form>
Thanks for reading. please clear my doubt..
To be clear, input elements will return a string when you call "value". So in your example you would need to change the subtraction equation to:
var totalfees = parseFloat(oldbal) - parseFloat(paid);
You can use parseFloat to create a float from a string or parseInt if you don't need decimal precision.
You should probably also change you HTML code to make the DOM level 0 event "change" rather than keyUp. Its more consistent across a range of different browsers (Desktop, Mobile, Tablet).
Change
var oldbal= parseInt(document.getElementById('totalfees').value);
to
var oldbal = parseInt(document.getElementById('oldbal').value);
Function should then look like
function doMath()
{
var oldbal = document.getElementById('oldbal').value;
var paid = document.getElementById('paid').value;
var totalfees = parseInt(oldbal) - parseInt(paid);
document.getElementById('totalfees').value = totalfees;
}
I believe you were retrieving the wrong input element.

Retrieve data from mysql and update them accordingly

I want to retrieve data from my MySQL database and display it as a table (I don't mind any style, but preferred as a table). Then the data should display with a radio button or a normal button which update that specific row and changing a single column in that row to Active (Status making Active).
I have started it, but I still have issues with adding a radio button or a button. Then I thought of displaying the information in a table which inside a form. This form will have each radio buttons, when the person select that radio button and press submit. The data should be updated in the MySQL database.
Can someone guide me about this? I'm a bit confused. I'm confused because I have to add a form and in that form I have to add a table and all this stuff should be in a php file.
on formpost.php page you can do something like this for handling the list array you received from the previous page:
<?
$list = $_POST['list'];
foreach ($list as $key => $list_php)
{
$query1 = "SELECT * FROM `stu_entry` WHERE `stu_entry`.`Student_No` = '$list_php' AND `stu_entry`.`Out_Time` = '0000-00-00 00:00:00'";
$result1 = mysql_query($query1);
$row1=mysql_fetch_array($result1);
//whatever you want to do
}
?>
I forgot to tell you something in the previous post. In the form page, lets say you have 100 rows with 100 checkboxes. It would be nasty to manually check or uncheck all of them. As an alternative you could append a little script at the end of the page to handle the checking/ unchecking process for you:
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
function countChecks(form){
var t=0;
var c=form['list[]'];
for(var i=0;i<c.length;i++){
c[i].checked?t++:null;
}
return t;
}
</script>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.formpost['list[]'])">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.formpost['list[]'])">
<i>with selected: </i>
<select name="submit_mult" id="submit_mult">
<option value="todo1">Action 1 </option>
<option value="todo2">Action 2 </option>
</select>
<input type="button" name="go" value="Go" onClick='if(countChecks(this.form)>0) {if(confirm("are you sure you want to \""+document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].text+" "+countChecks(this.form)+" items selected"+"\"")) {document.getElementById("referenceToSomeHiddenElement").value=document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].value;document.getElementById("formpost").submit();}} else alert("you have not selected any item!!")' >
Tell me if you need more help on this.
I first specify a MySQL command which in return gives me an array. I use a while statement to do something to each item in the array. The array is populated with the field name and the field contents.
$mysql = mysql_query("SELECT * FROM table");
while ($array = mysql_fetch_array($mysql))
{
$output .= '<form>Row: ' . $array['fieldname'] . ' <input type="button" value="Update" /></form>';
}
This extracts all rows from the table and adds a form to the variable $output for every result. I'm unsure of how you want to update your database, so you will have to look into it. You can use GET and POST methods.
Go ahead and try something like this. And tell me if that worked:
<p><b>your page name</b></p>
<form name="formpost" id="formpost" action="formpost.php" method="POST">
<table border="2" cellpadding="5" cellspacing="1" style="border-collapse: collapse" bordercolor="#999999" width="800">
<tr>
<td><b>Sno.</b></td>
<td><b>Field name1</b></td>
<td><b>Field name2</b></td>
<td><b>Field name3</b></td>
<td><b>Field name4</b></td>
<td><b>Field name5</b></td>
<td><b>Field name6</b></td>
<td><b>Field name7</b></td>
</tr>
<?
$sorting="";
if($orderby!="" && $direction!="") $sorting=" ORDER BY $orderby $direction";
$query = "SELECT * FROM table WHERE something = 'something' $sorting";
$result = mysql_query($query);
?>
<tr>
<?
$i=0;
while ($row = mysql_fetch_array($result))
{
$i++;
?>
<td><input type="checkbox" name="list[<?echo $i?>]" id="list[]" value="<?echo $row['some_primary_field_id']?>"><?echo $i?></td>
<td><?echo $row['Field1']?></td>
<td><?echo $row['Field2']?></td>
<td><?echo $row['Field3']?></td>
<td><?echo $row['Field4']?></td>
<td><?echo $row['Field5']?></td>
<td><?echo $row['Field6']?></td>
<td><p align="center">
<?
echo "<input title='button' name='change this row' value='Some Button' type='button' onClick=\"if(confirm('Press OK to change status to confirm')) {document.getElementById('someid').value='".$row['Field1']."';document.getElementById('formpost').submit();}\"/>";
?>
</td>
</tr>
<input type='hidden' name="hiddenlist[<?echo $i?>]" id="hiddenlist[]" value="<?echo "some boundry condition ".$row['Field2']?>">
<?
} //end of while
?>
</table>
</form>

Categories