creating dynamic variables in php to update multiple rows in MYSQL - php

I am currently working on an update profile section of a website I am creating for fun. In this part of the update profile business owners can update their restaurant menu (menu consists of category (appetizers, entrees, etc), menu item and allergens).
Right now the website is printing out what the business owner has previously submitted in input box format, this way business owners can simply just erase and re-enter their new information. However, we don't know exactly how many menu items each restaurant has so I devised a system to dynamically update each item being altered row by row.
<?php
$sql="SELECT * from menu_item as m, allergen as a WHERE a.restaurant_id=m.restaurant_id AND m.menu_item_id=a.menu_item_id AND m.restaurant_id='".$rest_id."'";
$result11=mysqli_query($con,$sql);
if (mysqli_num_rows($result)==0){
echo "<strong>You have not submitted any menu information</strong><br><br>";
echo "Please enter your menu information here: ";
echo 'Create Menu';
}
else{
$i=0;
echo "<table border='1' cellpadding='10'><tr><th>Category</th><th>Menu Item</th><th>Allergen</th></tr>";
while($rows=mysqli_fetch_assoc($result11)) {
echo '<tr><td><input type="text" name="category'.$i.'"value="'. $rows['category']. '"</td><br>';
echo '<td><input type="text" name="menu_item'.$i.'" value="'. $rows['menu_item']. '"</td><br>';
echo '<td><input type="text" name="allergen'.$i.'" value="'. $rows['allergen']. '"</td><br>';
echo '<td><input type="hidden" name="id'.$i.'" value="'. $rows['menu_item_id']. '"</td></tr><br>';
$i++;
}
}
echo "</table>";
var_dump(mysqli_num_rows($result11));
// var_dump($_POST);
$count=0;
while ($count<=mysqli_num_rows($result11)){
${"category".$count}=mysqli_real_escape_string($con, $_POST['category'.'$count']);
$count++;
}
var_dump($category0);
?>
This is where the while loop near the bottom comes into play. I want to be able to dynamically create variables for category, menu item, and allergen. Then I want to be able to create $result variables within this same while loop (mysqli_query) and then update rows accordingly. However, right now my very last var_dump is returning a value of "" which tells me I'm either concatenating the html name attribute wrong(first while loop) or there is something wrong with concatenation in my last while loop. Does anyone know what I'm doing wrong?

$_POST['category'.'$count'] in your second loop should be $_POST['category'.$count]. You also only want to run this code after the form has been submitted (I'm assuming the code you've posted is not your full script so it's not clear if that's what is happening) - otherwise you'll get the original values rather than any changes the user has made in the form.
In general you'll have an easier time if you can get the submitted data into a multi-dimensional array which you can loop through, instead of having to dynamically create variables. See the section "How do I create arrays in a HTML form?" on http://php.net/manual/en/faq.html.php. In your case I'd do something like:
// (in your first while loop)
echo '<input type="text" name="menu['.$i.'][category]" value="'. htmlspecialchars($rows['category']). '"><br>';
echo '<input type="text" name="menu['.$i.'][menu_item]" value="'. htmlspecialchars($rows['menu_item']). '"><br>';
// (etc.)
You then loop through this with something like:
foreach ($_POST['menu'] as $menuRow) {
// you now have:
// $menuRow['category']
// $menuRow['menu_item']
// ...and so on
}
You also want to escape the input values you are outputting with htmlspecialchars() as I have above.

Related

How to enable onclick type events with the output of a mysqli_fetch_array($result))

I have been trying to get my head around how to approach this problem. I am writing a web page book library with the categories ('nodes') as MySQL records. I want to print the list of categories at each level, starting at the highest level, and then allow the user to select a category to travel deeper into the library. The PHP codes runs a saved procedure in MySQL:
//loop the result set
while ($row = mysqli_fetch_array($result)) {
if ($row[1] <> 0) {
echo $row[0];
echo "<br />";
} else { // the first row is just the heading
"</strong>Category: ";
echo $row[0];
echo " : <br />";
}}
Because there are only two test categories, this produces output:
Books :
Nature
Children's Books
However, I want to be able to create an onclick event over 'Nature' and 'Children's Books' so the user can select a category and drill down t the next level via a php function. I can convert the php output into html eg:
<?= "<p>{$row[0]}</p>" ?>
but I can't see how I can identify the row in an onclick event to pass a parameter to the function. Perhaps I need to have a completely different approach?
Add an onclick attribute to the element that calls a JavaScript function that does what you want.
<?= "<p onclick='someFunc({$row['id']})'>{$row[0]}</p>" ?>
Replace id with the actual name of the column containing the ID of the row in the table. someFunc() can use that ID to look up information in an array or object, or send an AJAX request.

PHP multidimensional array from HTML form

I've got an HTML form that allows a user to submit details about one or more children. Each child can have one or more items.
My HTML form structure looks like this:
<input type="text" name="child[1][name]">
<input type="text" name="child[1][dob]">
I then have a table display for the items (as there are 2 fields per item) where the user can add/remove rows via Javascript. Example:
<table>
<tr>
<td><input type="text" name="child[1][item][name]"></td>
<td><input type="text" name="child[1][item][value]"></td>
</tr>
</table>
When I access this data, I'm inputting the child data into a table, then I need to access the items per child separately, so they can be stored in an 'items' table (with the child ID which I'll grab from the database insert).
In my PHP, I'm looking to achieve something like:
foreach($_POST['child'] as $child) {
$child_name = $child['name'];
$child_dob = $child['dob'];
// insert child data to children table
foreach($_POST['item'] as $item) {
$item_name = $item['name'];
$item_value = $item['value'];
// insert item data to items table
}
}
My problem is that without the items, the child array looks fine when I print_r($_POST['child']). However when I include the items as per my HTML above, the array only outputs the last item added (whether there is one or more). I'm not sure if I'm correctly specifying the array for items in the input tags, or how I should then access in the PHP.
If anyone has any suggestions about where my syntax may be wrong, or if perhaps I'm approaching this in the wrong way, that would be much appreciated.
Figured this out.
As suspected, the naming format was wrong for the item input fields, meaning the sub array for items wasn't being posted correctly.
Updated to:
<input type="text" name="child[1][item][1][name]">
<input type="text" name="child[1][item][1][value]">

Foreach loop with PHP to show each entry in database in a separate text box

I have a table of questions, and I'd like to use a foreach loop to print out each question separately with a text box and a checkbox next to it. I then need to be able to take any question that is checked and do stuff to them--specifically, take the id of the question and place that in a junction table, as these questions are to be added to a printable file. (It's a test question database). I know how to do foreach loops, but I was wondering if this was possible, and how to iterate the values to make sure each textbox corresponds to a checkbox and the right values are obtainable.
I hope that makes sense.
You should just be able to do something like this:
(except that this is not a For Each loop, same concept applies)
<? for ($xlist=0; $xlist<9; $xlist++) { ?>
<input type="checkbox" name="checkSel" id="check_<? =xlist ?>"> <input type="text" value="<? =$yourValue ?>" name="quest" id="quest_<? =xlist ?>">
<? } ?>
That will paint out a checkbox and a question with the same identifier. That way you can make sure they relate to each other.
Create an incrementing integer for your loop and put this inside:
echo "<input type='checkbox' name='" . $loopIncrementVariable . "' value='" . $valueFromDatabase"'>";
You can do the same for the textbox, assigning it the same incrementing value from the loop. They will then both have the same id which can be used to match each other.

How do I pass rows from HTML form to PHP?

I'm written a PHP program to display a tab delimited file. The purpose of this is to allow the user to views the rows and select which ones they want by checking the checkbox given in the row for each record. After they hit submit I have a PHP program to display the values, but the problem is only the last row's ID is being passed. However, when the user hits the SUBMIT button I can see all the values for the rows checked:
process_form.php?download=5108&download=5110&download=5114
How should I parse this in process_form.php? I've done a var_dump of $_POST and also
$_REQUEST but it only shows the last value which is 5114. I kind of understand the problem, most of the time in forms programmers only get one value per input field, but what happens when there are many records? It doesn't seem they should all have their own unique 'name'.
<td align=center><input type="checkbox" name="download" value="<?php echo $row['ID']; ?>"></td>
I'm doing something wrong here, but I'm not sure what. Is there a way to pass an array (I'm guessing) of IDs? Or should I be looking at parsing the URL of ?download=5108&download=5110&download=5114 because it has all the values I need there? If so, how do I do that? Thanks!
This is my solution:
<td align=center><input type="checkbox" name="download[]" value="<?php echo $row['ID']; ?>"></td>
Notice that download is now download[], thus creating an array to be passed to the PHP program to process the form.
Then using this demo PHP code I was able to get access to the array:
$my_array = ($_REQUEST["download"]);
print_r($my_array);
echo "<P>";
foreach ($my_array as $value)
{
echo $value . "<BR>";
}
I'd rather use your rowID to identify the name of <input> instead of the value.
<td align=center><input type="checkbox" name="download_<?php echo $row['ID']; ?>" value="1"></td>
Then you can process your request array like:
foreach( $_REQUEST as $key => $value ) {
if( preg_match('/^download_([0-9]+)$/', $key, $reg ) {
$rowId = $reg[1]; // Your row ID
$isChecked = $value; // State of checkbox
}
}
The row ID is parsed from variable name using regexp.
EDIT:
As mentioned in comments, this is not the simplest way to read an array of checkboxes. The simpliest is to name checkboxes download[] and parse this array in PHP then.
However, this is more universal, for example when you need to get array of input texts instead of checkboxes.

PHP Mysql & Jquery dynamically populating multiple records

I want to above Master and child system by using PHP,MYSQL & JQuery.
I am attaching sample image link below See screenshot
Product Quantity and UOM is field which belong to MAster Table and
Code, Component, category, quantity (Also) & UOM (duplicate) is belong to Child table.
I want to add Code, Component, category, quantity etc multiple time whenever user click on add.
Just need to know how can i save all these multiple records when someone completed their works and click on Final Save Button?
I am really and very aggressively searching for this but didn't get any anwer.
If anyone who can find the way or any help or anything that will help me towards this system.
Thanks a lots pls pls Help
you'll want to use
jQuery ajax to save data
.clone() to add a record in the UI you'll have to reset the values will your at it
that should get you started
Each time your user clicks 'add' you want to take the values of your form inputs, build a new table row and show their selected values. This is easy enough, but you also need to add hidden inputs which represent what they chose in the select boxes above, so when the user clicks save, the whole form is posted and you can process the input. A simple example would be:
<script>
var count = 0;
$('#add').click(function(event)
{
var code = $('#code').val(),
component = $('#component').val()
category = $('#category').val(),
uom = $('#uom').val();
$('#table').append(
'<tr>'
+ '<td>' + code + '<input type="hidden" name="record[' + count + '][code]"></td>'
+ '<td>' + component + '<input type="hidden" name="record[' + count + '][component]"></td>'
+ '<td>' + category + '<input type="hidden" name="record[' + count + '][category]"></td>'
+ '<td>' + uom + '<input type="hidden" name="record[' + count + '][uom]"></td>'
+ '</tr>'
);
/*
EDIT: I changed this to a DECREMENTOR so our keys don't overlap and override
anything that is CURRENTLY in the database
*/
count --;
})
</script>
This would attach a click handler to the add button. Each time it is clicked, we get the values of the inputs, store them in a variable, and build + append a new table row to your "preview table" below, which shows the values they selected and creates hidden inputs which can be processed later after the user clicks Save.
Some notes about this:
- it only gets the value of the selected inputs (so for the select boxes, the value of the option not the text. you'll have to do some extra work to replace that into your table row.
- your entire table will have to be encapsulated in a <form> tag, which your save button must also be inside.
Once you get the posted data to the server, do a print_r($_POST) to see what it looks like, you should be able to figure out how to process it fairly easily.
edit
Okay, so you asked a lot of questions here, i'll try to address them as best I can, without writing a novel.
What if someone mistakenly clicks on add and wants to cancel the addition (or changes their mind, whatever).
This actually isn't that hard. If this happens, just remove the appended table row from your table using $.remove. Since all the hidden input elements are contained within the table row, they will also be removed from the form so when the user posts, the fields will not be present.
How should you sanitize the data?
Sanitize the data when the user clicks add, as you populate the form, instead of afterwards, just before you post the form. It will be easier to deal with the input errors when the user clicks add than it will be to deal with them when they click save.
How can you use this method if you want to modify existing records in the database?
There's a few different ways you can handle this. The easiest way is to pre-populate your form with table rows for each existing row in your database, and add an id (assuming you have an auto-increment primary key for each row) input value for that record on the table row. This way when you're processing the form, you'll be able to see if it's an existing record by checking for the existence of the id in the posted data and verifying that it exists in your database. If it doesn't have an id key you know that it is a new record and you need to do an INSERT, and if it does, you can do an UPDATE or leave the record be. For DELETED rows, you'll want to loop through your POSTed data before doing any INSERTs and gather the id values that have been posted and run a query something like DELETE FROM table WHERE ID IN (<list of posted ids>). This will delete any rows that the user removed, then you can loop through the POSTed data again and insert the new rows.
An example of pre-populating this table would look something like this:
<?php
$query = "SELECT * FROM bill_items WHERE bill_id = 123";
$result = mysql_query($query);
$materials = array();
while ($row = mysql_fetch_assoc($query))
{
$materials []= $row;
}
?>
<? foreach ($materials as $material): ?>
<tr>
<td>
<?= $material['code']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][code]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['component']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][component]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['category'];
<input type="hidden" name="record[<?= $material['id']; ?>][category]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['quantity']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][quantity]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['uom']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][uom]"
value="<?= $material['uom']; ?>">
<input type="hidden" name="record[<?= material['id']; ?>][id]"
value="<?= $material['id']; ?>">
</td>
</tr>
<? endforeach; ?>
Also, a note. I changed the javascript example code above. I changed count++ to count-- because when you pre-populate the form with data that is currently in the database you are going to use the id of the material in the input key. When a user adds new data, there is a possibility that the key generated with javascript (with count++) will collide with the existing table data. To rectify this, we change it to count--. This key (in javascript) really isn't important, it's just keeping our data grouped together, so a negative value here does not affect anything.

Categories