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>
Related
I am trying to make a rating system using multi-select dynamically generated from rating text on the database. The final result should look like this: Rating Service but now I need to save selected option after save is clicked.
in the database there is two table the first one have 2 column the first is the id and the second is the text of the rate
the second table is where i wont to save the selection that the user chose using php
page code
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>About</th>
<th>Provider</th>
<th>Rating</th>
</tr>
</thead>
<?php
$query_rate_text = "SELECT * FROM rateing_text";
$selecting_rates = mysqli_query($con,$query_rate_text);
$i = 0;
while($row_rate = mysqli_fetch_assoc($selecting_rates)){
$rate_id= $row_rate['rate_id'];
$rate_text= $row_rate['rate_text'];
$i++
?>
<form name="rating_form">
<tbody>
<tr>
<td><?php echo $i ?></td>
<td> <?php echo $rate_text ?></td>
<td><span class="badge badge-danger">
<?php echo $provider_name ?></span></td>
<td>
<select name="p<?php echo $i ?>">
<option value="1">Very Bad</option>
<option value="2">Bad</option>
<option value="3">Good</option>
<option value="4">Very Good</option>
<option value="5">Excelent</option>
</select>
</td>
</tr>
</tbody>
<?php } ?>
<tfoot>
<tr>
<td colspan="3"><button type="submit" name="save_rate"> Save </button> </td>
</tr>
</tfoot>
`enter code here`
</form>
</table>
How can I get info form the select and save them to the database ?
Radio button is much better than <select>.
The rate id and selected value must be passed as a key=>value
You need to stop using Word Press syntax.
Learn to use Herdoc Syntax
Using SELECT * is a poor standard practice.
Fetch array and assign values with a list
This code is untested.
<?php
echo <<<EOT
<form name="rating_form" action="#">
<table class="table table-striped">
<tr><th>#</th><th>About</th><th>Provider</th><th>Rating</th></tr>
EOT;
$query_rate_text = "SELECT `rate_id`,`rate_text` FROM rateing_text WHERE 1 ORDER BY `rate_id`";
$selecting_rates = mysqli_query($con,$query_rate_text);
$i = 0;
while(list($rate_id, $rate_text) = mysqli_fetch_array($selecting_rates)){
$i++;
echo "<tr><td>$i</td><td>$rate_text</td><td>$provider_name</td><td>5<input type="radio" name=\"$rate_id\" value=\"5\" /> 4<input type="radio" name=\"$rate_id\" value=\"4\" /> 3<input type="radio" name=\"$rate_id\" value=\"3\" /> 2<input type="radio" name=\"$rate_id\" value=\"2\" /> 1<input type="radio" name=\"$rate_id\" value=\"1\" /></td></tr>\n";
}
echo '</table><button type="submit" name="save_rate"> Save </button></form>';
?>
UPDATE
thank you very much that's helped to understand new way's,one more
thing how can i get the data out from this radio 5 buttons to insert
them to the database to the table named rating which have let's say 3
column id and provider name and the rate it self , again thank you for
helping
The radio input type is a more user friendly way then the cumbersome select.
The way I setup the radio buttons with the rate_id as the "name" so the selected "value" is passed as a key=>value pair to the form's action script.
Your select name should also contain the rate_id
The problem your code has is, the action script will receive will receive keys of sequential numbers that have no meaning and difficult to know how many were posted by the form.
To pass the provide name add a hidden input type:
<input type="hidden" name="provider" value="$provider_name" />
And I would remove the provider from the table td.
Not knowing your rate_id convention I could not improve the radio button naming convention.
The way I would do it is when passing key=>value pairs I would begin the key "name" with a unique character where no other "name" in the form would start with that character.
For example if the rate_id is a numeric value I may prepend a 'k' to the numeric key value.
So instead of
name=\"$rate_id\"
I would use
name=\"k$rate_id\"
The in the receiving action script I would get the key=>values like this
$provider_name = $_GET['provider']
foreach($_GET as $key => $value)){
if(substr($key,0,1) == 'k'){
$rate_id = intval(substr($key,1));
$rating = intval($value);
$sql = "INSERT INTO `table` (`rate_id`, `provider_name`, `rating`) VALUES ($rate_id, '$provider_name', $rating)";
mysqli_query($link,$sql);
}
}
so the requirement is to have a table which allows the user to create a new estimate online. I went as far as adding rows/ deleting them, having my DB's product list on the product field. But once I select the product, I would like the field 'Price' to pull up its price.
Here's the code I am currently using:
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD><INPUT type="text" name="txt"/></TD>
<TD>
<SELECT name="country" onchange="getPrice(this.value, this.closest('tr').rowIndex);">
<?php while($row = mysql_fetch_array($query)) {
echo '<option value="' .$row['nom'] . '">'.$row['nom'].'</option>'; }
?>
</SELECT>
</TD>
<TD><INPUT type="text" name="txt"/></TD>
</TR>
</TABLE>
Ok, so what I assume is that your javascript function getPrice(name, tablecell) should retrieve the price stored in your database and puts it's price-value into the given table cell.
Before I write out a possible solution, I would like to add: This solution will keep the values from the database in a client-side array. Thus visible for any user, reviewing the code of your page. This shouldn't be an issue if you only store non-critical information though.
// For testing purpose i filled in a mini-json, but in
// the PHP-example later this post you will find a short
// example how to fill this with PHP from your database
var prices = {
'test_prod_1' : 16.46,
'test_prod_2' : 21.55,
'test_prod_3' : 7.4
};
function getPrice( prodID, tableCell )
{
if (typeof prices[prodID] !== 'undefined')
tableCell.innerHTML = '€' + prices[prodID]; // Get the price from the pre-loaded price information
else
tableCell.innerHTML = '?';
}
<input type="button" value="click me" onClick="javascript:getPrice('test_prod_2', document.getElementById('test_cell'));">
<table border=1 cellspacing=0 cellpadding=5>
<tr>
<td>Product name</td>
<td>price</td>
</tr>
<tr>
<td>test</td>
<td id="test_cell"></td>
</tr>
</table>
And then with PHP You would be able to create this price list dynamically. But, remember that the data is visible client side, so this example will only select the price and name/id data. Make sure to edit the variable names to the ones you use.
<script type="text/javascript">
var prices = <?php
$js_pricelist = array();
// Retireve the information from the server's database. Assume that $result is a result set in an ASSOC
foreach( $result as $row )
$js_pricelist[ $row['prodID'] ] = $row['prodPrice'];
echo JSON_Encode( $js_pricelist );
?>
</script>
Please check the last script as I haven't tested it yet, and is meant more to give you an idea of the possibilities
Conclusion: The main idea is, that once you load the page, you assemble a javascript object containing all price data (Using PHP). You echo this object to a javascript block, and make a function that reads from this newly created array/object to retrieve the price that corresponds to the product_id.
<table width="200" border="0">
<tr>
<td><p>
<?php while($row1 = mysql_fetch_array($res)){ ?>
<label>
<input type="checkbox" name="module" value="<?php echo $row1['MID']?>" id="<?php echo $row1['MID']?>">
<?php echo $row1['ModuleName']?></label>
<br>
<?php }?>
</p></td>
</tr>
</table>
I use this code to outout the checkboxes,and the checkboxes appear allright.
I m not sure about how,the data can be saved to the MYSL table.
the table i drew is in the form:
student_module{studentID,ModuleID}
what is the code i should write to enter the data to that table.
One student can enroll to many modules.
Using ajax functionality:
By clicking on checkbox collect the value of studentID and ModuleID and pass to the ajax method and then in your server end page, you can update db record.
Without ajax functionality
Post the form when user clicking on checkbox or put a save button below to submit the form on a PHP page and then you can collect all your values and update db accordingly.
<input type="checkbox" name="chk1[]" value="" ><?php echo $row1['ModuleName']?>
if(isset($_POST['submit']))
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
// now here in your insert query take mid='".$selected_checkbox."';
}
I have no idea how to basically use this. Im thinking of using javascipt arrays though.
Well I have a select option here with values from the database and the select is dynamic. The "add row" button will add another row of option select:
<td>Items </td>
<td style="text-align:left;">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" >
<TR>
<TD><INPUT type="checkbox" name="chk[]"/></TD>
<TD>
<select name="ItemNo[]" id="select" value="ItemNo" onChange="this.disabled=true;">
<?php
$sql2="select * from jewelry_system.item where NumStored !='0' order by ItemName asc";
$result2 = mysql_query($sql2);
while($row2=mysql_fetch_array($result2)){
?>
<option value="<?php echo $row2['ItemNo']?>">
<?php echo $row2['ItemName'];?>
Php:<?php echo $row2['SalePrice'];?> </option>
<?php } ?>
</select>
</TD>
</TR>
</TABLE>
</td>
</tr>
Here is what should be changed by ajax?
<tr>
<td>Total Payment (Php):</td>
<td> <div id="tpayment">0.00</div> </td>
</tr>
I wanted to compute total payment onChange of the values in the select option. and since the value can only be changed once should i use arrays? I'm quite clueless to ajax, tried learning at w3schools but failed.
pls thanks
You might not need AJAX unless you are needing to set something in your database prior to clicking a "submit" button of some sort. It looks like you should be able to store all the information in your selects when you build your page with PHP. You would need to show/hide your selects in the document using javascript.
Add ;updateTotal() to your select onChange event:
<select name="ItemNo[]" id="select1" value="ItemNo" onChange="this.disabled=true;updateTotal()">
Then add this function to your page or your javascript file:
<head>
<script language="javascript" type="text/javascript">
function updateTotal() {
var dropdown = document.getElementById('select1');
var total = 0;
for (var i=0; i<dropdown.length; i++){
if (dropdown.options[i].selected) {
total += dropdown.options[i].value;
}
}
document.getElementById('tpayment').innerHTML = total;
}
</script>
</head>
Since you're going to be adding/removing rows, you will need to keep track of them like you mentioned with an array - probably a global one.
at the beginning of your javascript, declare a global array to store your datatables like this:
var selects = new Array();
You'll also want to update your add/remove calls:
<INPUT type="button" value="Add Row" onclick="addRow('dataTable','select1')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable','select1')" />
Then, when you call your addRow function, do this:
function addRow(rowname,selectname) {
/* ... original function stuff ... */
selects.push(selectname); /* this will add the selectname to the selects array */
}
And likewise, when you call your removeRow function, do this:
function removeRow(rowname,selectname) {
/* ... original function stuff ... */
selects.splice(selects.indexOf(selectname),1);
updateTotal(); /* since selected items might have been removed */
}
And lastly, we'll modify our original function like this:
function updateTotal() {
var total = 0;
for (var h=0; h<selects.length; h++) {
var dropdown = document.getElementById(selects[h]);
for (var i=0; i<dropdown.length; i++){
if (dropdown.options[i].selected) {
total += dropdown.options[i].value;
}
}
document.getElementById('tpayment').innerHTML = total;
}
}
I have a PHP page displaying the results of a MySQL query. It adds checkboxes to each row. The selected rows are then inserted into another table on submit.
My application is a Transport planning platform. I am looking for a way to display the total weight of the selected rows in real time, a box at the top of the page dispalying the current sum of the selected rows.
Can anybody guide me on how to add this functionality to my existing page.
My code currently is shown below:
<?php
mysql_connect("localhost", "username", "password")or die("cannot connect");
mysql_select_db("databasename")or die("cannot select DB");
$sql="SELECT `crtd dept`,`customer`,`case no`,`gross mass` from despgoods_alldetails where transporttypename= 'localpmb'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table border=1>
<tr>
<td>
<form name="form1" method="post">
<table>
<tr>
<td>#</td>
<td>Dispatch Area</td>
<td>Customer</td>
<td>Case Number</td>
<td>Weight</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><input type="checkbox" name=check[] value="<?php echo $rows['case no']; ?>"></td>
<td><?php echo $rows['crtd dept']; ?></td>
<td><?php echo $rows['customer']; ?></td>
<td><?php echo $rows['case no']; ?></td>
<td><?php echo $rows['gross mass']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan=3><input name="Next" type="submit" id="Next" value="Next"></td>
</tr>
<?php
$check=$_POST['check'];
if($_REQUEST['Next']=='Next'){
{
$sql="INSERT INTO loaddetails (dispatcharea,Customer, casenumber, weight,LOCStatus)
SELECT `crtd dept`,Customer,`case no`,`gross mass`,'in Load Creation'
FROM despgoods_alldetails WHERE `Case No` = '$val'";
foreach($check as $key=>$value)
{
$sql="INSERT INTO loaddetails (dispatcharea,Customer, casenumber, weight,LOCStatus)
SELECT `crtd dept`,Customer,`case no`,`gross mass`,'in Load Creation'
FROM despgoods_alldetails WHERE `Case No` = '$value'";
$final=mysql_query($sql);
if($final)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=planlocalpmbstep2.php\">";
} }
}
}
// Check if delete button active, start this
// if successful redirect to php.php
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
The output of the above code is shown below:
As the others have said, you'll have to do this in Javascript, since it'll be on the client side. I'll assume that you're not using a library such as jQuery or Prototype on this page, and if this is all you're doing, it'd be massive overkill to use one of them.
First, add a HTML element which will contain your total:
<div>Total: <span id="total">0</span></div>
The bit of information you really need to know however, is the weight which corresponds to each checkbox. The simplest method would be to store it on the checkbox element itself. Add an attribute called data-weight. eg:
<input type="checkbox" name="check[]" value="12" data-weight="1234" />
Then, add some javascript:
<script>
(function () {
var totalEl = document.getElementById('total'),
total = 0,
checkboxes = document.form1['check[]'],
handleClick = function () {
total += parseInt(this['data-weight'], 10) * (this.checked ? 1 : -1);
totalEl.innerHTML = total;
},
i, l
;
for (i = 0, l = checkboxes.length; i < l; ++i) {
checkboxes[i].onclick = handleClick;
}
}());
</script>
Aaaannd here's a working demo for you! http://jsbin.com/ipeduf
Assuming you don't want to have to refresh the page every time the user changes a selection, you need to do this in the browser, in Javascript, not in PHP.
I think that you can use a javascript function.
Add an onClick attribute to every checkbox (if you don't want a submit button):
<INPUT TYPE="checkbox" NAME="switchBox" onclick="myfunction(this)">
Then myfunction should calculate the value with something like that:
<script language="javascript">
var total;
myfunction(checkboxId){
total = total + checkboxId.value;
}
</script>
Please notice that this is an unchecked example, only to give you an idea about a solution.
To avoid the need to submit and reaload the page on changes, I would use javascript / jQuery.
What I would do is:
attach all individual weight values to the table rows (or checkboxes...) using the html5 data attribute: <tr data-weight="1604"> for your first row;
on a checkbox value change, loop through all rows that have a selected checkbox to get and generate your sum. That would be something like:
$("input").change(function(){
var total_sum = 0;
$('input').is(':checked').each(function(){
total_sum += $(this).parents("tr").data("weight");
});
});
(can't get the formatting right...)
display the sum in the box you want.