How to colect data from dynamicaly created php table - php

I'm new in php and webdevelop so i have simple problem.
Background of the story:
I have form in PHP (table) where I keep gifts list.
There are 3 column: number, gift description and info who booked gift (or if no one booked target gift, there is input text file that allow to book gift).
At the end of table there will be place to propose your own gift idea.
<?php
db_connect();
$result = mysql_query("SELECT GIFTS_ID, USER_DESCR, GIFT_DESCR FROM GIFTS");
$array = array();
while ($row_user = mysql_fetch_assoc($result))
$array[] = $row_user;
$howManyRows = mysql_num_rows($result);
db_close();
?>
<form action="" method="post">
table id="PersonList">
<thead>
<tr>
<th>Lp </th>
<th>Gift Description </th>
<th>Reservation </th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="2">
<input type="submit" name="send" value="Send">
</th>
</tr>
</tfoot>
<tbody>
<?php
foreach ($array as $gifts) {
echo '<tr>';
echo '<td class="number">' . "{$gifts['GIFTS_ID']}" . '</td>';
echo '<td class="description">' . "{$gifts['GIFT_DESCR']}" . '</td>';
echo '<td class="reservation">' . selectWhatToDisplay("{$gifts['USER_DESCR']}") . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</form>
<?php
function selectWhatToDisplay($USER_DESCR) {
if ($USER_DESCR == 'N')
{
return '<input type="text" name="reserv_data[]">';
}
else
{
return $USER_DESCR;
}
}
?>
As u see rows are created dynamicaly when user open website.
PROBLEM:
I want allow user to book more than one gift in single "Send" operation but I dont know how to collect data from dynamic created table: what rows was the target and what was data in single text field.
---EDITED---
My problem is that now i have multiple id named "reserv_data[]" as input field. Normal way to reach this kind of field is $_POST['name_of_field']. Now I dont know how to get (ie 5'th input file - 5'th means from 5'th row of table).

You can use javascript to select all the input fields and then check which of those have a value that's long enough(longer than 0 i guess).
Once you have the array of inputs you can organize them into a nice ajax call to the server.
All your inputs can be structed like this :
<input data-bookID="BOOK_ID" type="text">
This way you have all the information you need, the BOOK_ID can be generated dynamically when you construct the table.
I hope i understood your question properly :P

Related

i need to save info from multi dynamic select using to database

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

Using a PHP generated webform and mySQL to update multiple rows in a table

I have created a database to store results in a competition along witha php generated web-page that lists all the competitors followed by a textbox in which to record their score.
When I press the submit button I want it to update all of the rows in the table.
I'm new to php and mySQL, I can do it for one of them at a time but I don't want them to have to press 30+ individual submit buttons to handle each row.
The following code generates the form:
<?php
$field_event_id = $sports_day_id = "";
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )
$field_event_id = $_POST["field_event"];
$sports_day_id = $_POST["sportsday"];
$query = "SELECT * FROM student JOIN participants ON student.student_ID = participants.student_ID WHERE `Field_Event_ID`= $field_event_id";
$result = mysqli_query( $dbc, $query ) ;
echo '<body>';
if ( mysqli_num_rows( $result ) > 0 )
{
echo'<header> <h1> Please enter the results below </h1> </header>';
echo '<table align="center" border="1" cellpadding="10px" bgcolor="#DCF8FE">
<tr>
<th>Forename</th>
<th>Surname</th>
<th>Year Group</th>
<th>Score</th>
</tr>
<tr>';
while ( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ))
{
echo '<form action="Add_Scores_Field_Event_Register.php" method="post">
<td> <strong>' . $row['Forename'] .'</strong><br> </td>
<td> <strong>' . $row['Surname'] .'</strong><br> </td>
<td> <strong>' . $row['Year_Group'] .'</strong><br> </td>
<td> <strong> <input type="text" name="notes_input"> </strong><br> </td>
</tr>
</form>';
}
echo '</table>';
echo '<p><input type="submit" value="Enter scores" ></p>';
}
else
{
echo '<p>There are currently no students in this event.</p>' ;
}
{
# Close database connection.
mysqli_close( $dbc ) ;
}
# close body section.
echo '</body>';
# close HTML section.
echo '</html>';
mysqli_close($dbc);
?>
According to this post you can set the name attribute of elements to an array.
<input type="text" name="inputs[]" value="bob">
<input type="text" name="inputs[]" value="jim">
If you submit this through a form. You should be able to access the values like:
$_POST["inputs"][0]; // bob
$_POST["inputs"][1]; // jim
So, if you output your information inside a form and setup the name attributes for the scores properly. When you submit the form, you should be able to grab all the scores (editted or not) and update your database with the values.
You will have to keep track of which record in the database to change.
The code I provided is untested; however, according to the linked post, it should work.
Don't forget to learn about prepared statements as Alex Howansky had commented. These are really important.
If you try this out, you would need to move your form tags to wrap the entire table; instead of, particular rows.
EDIT:
With a little more though I see 2 solutions:
Place the student ID inside a hidden tag and use the name attribute to send it along with the other data.
<input type="hidden" name="studentIds[]" value="<place student id here>">
I would place the input tag in the td for your forename; because, it is the first td and one of the tds that uniquely represents the row.
OR
Use the Student ID as the index for your index and the score as the value.
<input type="text" name="notes_input[<place student id here>]">
You can then iterate through notes_input and get the key and value:
foreach ($array as $key => $value) {
//code
}
See documentation for more information.

How to get selected product's price and show it on table?

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.

Sending a SQL command with one click of an HTML button through PHP

So, I have a basic PHP site that brings up a list of salespeople from a MySQL server when a selection from a drop-down box is submitted. I've set up a button to appear next to each result, and I want a php script to run when the button is clicked using MySQL data from that specific result. Everything works except the button that runs the second MySQL query. Here's an example of the table after the first query:
<table border="1">
<tr>
<td>Last name</td>
<td>First Name</td>
<td>Job Title</td>
<td>City</td>
<td>Client List</td>
</tr>
<tr>
<td>Bondur</td>
<td>Gerard</td>
<td>Sale Manager (EMEA)</td>
<td>Paris</td>
<td>
<form method="POST" action="empLookup.php">
<input type="submit" name="empLookup" value="Look up clients"
</td>
</tr>
</table>
By clicking on the button I would run a MySQL command like 'SELECT clients FROM blah WHERE employeeNumber = ?'
I don't have a problem with any of this except passing the value from the button to the PHP script.
This is what my PHP code looks like for handling the form submission and display of results. The button(s) in question are in the HTML table in the foreach loop.
<?php #this is the default php file for looking up Employees
$page_title = 'Our Associates by City';
require ('./pdoConn.php');
$sql = "SELECT DISTINCT city from Offices";
echo '<h1>Our Associates by City</h1>';
Type in a Name to view Years</a><br>';
//create the form
echo 'Please select a year: <br>';
echo '<form action="index.php" method="post">';
echo '<select name= "city">';
foreach($conn->query($sql) as $row)
{
//each option in the drop down menu is each and every year
//brought up by the query
echo '<option value ="'. $row['city'].' ">'. $row['city']. '</option>';
} //end of foreach
echo '</select>'; //end drop down menu
//now to create the submit button
echo '<br><input type="submit" name="submit" value="List"><br>';
echo '</form>'; //end of form
//This if statement runs when the submit button is clicked
if ($_SERVER[REQUEST_METHOD] == 'POST')
{
$flit = $_POST[city]; //the city variable from the HTML form will be used
echo '<br><br>';
$sql2 = "SELECT employeeNumber,lastName,firstName,jobTitle,city
FROM Employees,Offices
WHERE Employees.officeCode = Offices.officeCode AND city = ?";
$stmt = $conn->prepare($sql2);
$stmt->execute(array($flit));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'Contact any of our local staff: <br>';
//create a table of employees
echo '<table border="1"><tr><td>Last name</td><td>First Name</td>';
echo '<td>Job Title</td><td>City</td></tr>';
//time to populate the table, this loop runs for each entry
foreach($rows as $r)
{
echo '<tr><td>'.$r[lastName].'</td><td>'.$r[firstName].'</td><td>';
echo $r[jobTitle].'</td><td>'.$r[city].'</td><td>';
echo '<form method="POST" action="empLookup.php">';
//now to make the button which will search the employee's client list
echo '<input type="submit" name="empLookup" value="Look up clients"</td></tr>';
} //end foreach
echo '</table>';
} //end if server request post thing
?>
I does not completely understood your exact requirement but I think you want employee number into your button if this is your requirement then you can simply check this code
`echo '<input type="submit" name="empLookup" value="'.$r['emp_id_from_database'].'"</td></tr>';`
From your html code, your form looks empty.
You need to add the data to your html form. If you want to avoid the user to see you can use fields. Like it was in the comments said, use $variableName instead of ? in your query. Don't forget use \"$variableName\" to avoid mysql injections.
I took a second reading of your code: You realy should read a php book completly before you program stuff for productive company websites. There are beginner mistakes in your code. And some beginner mistakes leads to insecure websites. I hope this doesn't look an offense, but like an advise.

Saving the selected rows by checkbox to database in php

I have a query to display all the records of the ebooks table from the database.
I displayed it in a table with a checkbox from the first column.
I'm trying to save the rows from the selected checkbox in the table width the Name of School but I don't have any idea.
I'm just a beginner in php, any help is appreciated. Here is my codes:
HTML codes:
$result1 = mysql_query("SELECT * FROM school GROUP BY SCHOOL_NAME");
while($row1=mysql_fetch_array($result1)) {
?>
<option><?php echo $row1['SCHOOL_NAME'];?></option>
<?php } ?>
</select>
<table class="table table-striped table-hover table-bordered datatable">
<thead style="background: #a83535; color: black;">
<tr>
<th style="width: 50px;"></th>
<th style="color: #3b3b3b;">Ebook Title</th>
<th style="color: #3b3b3b;">Category</th>
<th style="color: #3b3b3b;">File Name</th>
</tr>
</thead>
<tbody>
<?php
$result = mysql_query("SELECT * from ebooks ORDER BY EBOOK_TITLE");
$count = mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
?>
<tr>
<td>
<center><input type="checkbox" name="check[]" ></center>
</td>
<td><input type="" name="ebookname[]" value="<?php echo $row['EBOOK_TITLE'];?>"></label></td>
<td><input type="" name="ebookcategory[]" value="<?php echo $row['EBOOK_CATEGORY'];?>"></label></td>
<td><input type="label" name="ebookfilename[]" value="<?php echo $row['EBOOK_FILENAME'];?>"></label></td>
</tr>
<?php } //end of while loop ?>
</tbody>
</table>
<button type="submit" class="btn btn-hg btn-primary" name="AddEbooks">Submit</button>
I want to save the rows selected by the checkbox to database:
Table: school_management
Columns: ID_NUMBER, SCHOOL, EBOOK, FILE_NAME, DATE_ASSIGN
Values (from the HTML table to database): ('','$school_ebook','$ebookname','$ebookfilename','')
Here is the screenshot:
First, you will need to assign an ID number to the checkboxes so that you can differentiate each record. Using the ID_NUMBER would be ideal here. In your current script where you are displaying the checkbox, your line that reads this:
<center><input type="checkbox" name="check[]" ></center>
Should include the ID_NUMBER like this in the name. Additionally, a value should be assigned to the checkbox so we can verify later.
<center><input type="checkbox" name="check[<?php echo $row['ID_NUMBER'];?>]" value="1"></center>
Now you can go ahead and set up something that gets triggered when your form is submitted. You can essentially loop through each record and check it against the "check[ID_NUMBER]" checkbox to see if the value is 1. If the value is 1 then the record had been checked to save and you can then carry on saving the record.
How you want to handle the form is up to you - you could do AJAX to avoid reloading the entire page or you could do a simple form action="page_name_here.php" and handle the submission there. If you go about doing a simple form post without AJAX, it could be something like this -
Current page form tag:
<form name="" action="page_name_here.php" method="POST">
If you want to use the school_ebook var you need to assign the select options for the school_ebook a value:
<option value="<?php echo $row1['SCHOOL_NAME']'?>">
page_name_here.php:
<?php
/* Get the school name */
$school_ebook=$_POST["school_ebook"];
/* Query your books DB to get the records */
$result=mysql_query("SELECT * from ebooks ORDER BY EBOOK_TITLE");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
$bookID=$row['ID_NUMBER'];
/* Get the Book ID and now we have to fetch from $_POST the value from the form */
if (array_key_exists($bookID, $_POST["check"])) {
$ischecked=$_POST["check"][$bookID];
/* See if this has a value of 1. If it does, it means it has been checked */
if ($ischecked==1) {
/* It is checked, so now in this area you can finish the code to retrieve the data from the row and save it however you like */
}
}
}
?>
Once completed with your inserts, etc., it should accomplish what you need.

Categories