I have a dynamic output form where the text input fields have the same name. I need to loop through
the text inputs and insert multiple rows into the database for each text field input.
$sql="INSERT INTO orderitems (orderNum,productNum,quant)
VALUES
('$num1','$_POST[pNum]','$_POST[quant]')";
<input type="text" name="pNum" value="<?php echo $t1; ?>"> //may have several with same name
If you want to submit your form with multiple inputs with the same name, you should add [] to the name. Then you can use it on PHP-side as every array (i.e. looping with foreach)
<input type="text" name="pNum[]" value="<?php echo addslashes($t1); ?>">
(by the way, remember always about quoting)
and on PHP side:
foreach($_POST['pNum'] as $value)
{
// remember about quoting here, too
}
Soooo.... loop through them and insert multiple rows?
for ($i = 0; $i < count($_POST['pNum']); $i++) {
$sql = 'INSERT INTO orderitems (orderNum, productNum, quant) VALUES ('
. "'" . mysql_real_escape_string($num1) . "', "
. "'" . mysql_real_escape_string($_POST['pNum'][$i]) . "', "
. "'" . mysql_real_escape_string($_POST['quant'][$i]) . "'"
. ')';
}
Note the use of mysql_real_escape_string. Never, NEVER, NEVER inject values from $_POST or $_GET or $_COOKIE or any other value your user has supplied directly into a SQL statement. Besides the potential to break if the value contains a ', this can also be used maliciously to inject SQL that alters (or erases) your database.
You can insert many rows with an INSERT request, you have just to create it with PHP
http://dev.mysql.com/doc/refman/5.0/en/insert.html
Related
I have data stored in database in varchar format like for eg: S,M,L,XL , I have checkboxes for these in my php page. Is it possible to retrieve these from database and show already checked boxes in php/html. (When there is just XL value , only XL checkbox should be checked in html/php page )
I have done this in my project and I do not recommend.
You can store an enum array of values in PHP and then use it to create the form. Selecting the data from database is not different than any other query. You can then compare the value from the database to the value in your array.
define('SIZES', ['S', 'M', 'L', 'XL']);
$value_from_db = 'L'; // Fetched from the database
echo '<form>';
foreach (SIZES as $size) {
if ($value_from_db == $size) {
echo '<label><input type="checkbox" value="' . $size . '" name="size" checked />' . $size . '</label>';
} else {
echo '<label><input type="checkbox" value="' . $size . '" name="size" />' . $size . '</label>';
}
}
A better option would be to store these values in a reference table in the database instead of in PHP. You can then enforce the referential integrity. Instead of looping on the array, you would loop on the values from the reference table.
One way of doing is :
- you retrieve the database values using SQL in PHP
- Dynamically create the checkbox HTML using the retrieved values
I know that the formItIsSelected utility works perfectly well to keep the value of a Select field in a form when (for example) the form fails to validate for some reason. But has anybody tried to use this when a Select field populates from a table in MySQL? This is surely more useful than a Select field populated with static values..
I have a form in a modx site, hooked with formit and a select field in it retrieves dynamically values from a table in MySQL. When the form fails to validate this specific field loses the value the user has selected. My field (in the form) has the following setting:
<select id="Field245" name="typeOfRelationship" class="field select medium" tabindex="4">[[!getRelationshipOptions? &selected=`[[!+fi.typeOfRelationship]]`]]</select>
and the snippet and which works correctly simply does:
<?php if (!$modx->addPackage('contacts', MODX_CORE_PATH . 'components/contacts/model/')) {return 'Could not load xPDO model';}$current = $modx->getOption('selected', $scriptProperties, '');$output = [];$relationships= $modx->getCollection('RelationshipCodes');foreach ($relationships as $relationship) {$selected = $current == $relationship->get('codes') ? 'selected="selected' : '';$value=$relationship->get('descriptions');$output[] = '<option value="' . $relationship->get('descriptions') . '" ' . $selected . '>' . $relationship->get('descriptions') . '</option>';}return implode('', $output);
So far so good. But when I replace the $output[] line with:
$output[] = '<option value="' .$value . '" '. '[[!+fi.typeOfRelationship:FormItIsSelected=' ."'".$value. "'". $selected. ']]>' . $value . '</option>';
this fails! It doesn't error but it still allows the Select field to lose its setting when the form fails validation. Do you see a problem? Or maybe FormItIsSelected does not work in that context?
Many many thanks
I am creating radio buttons dynamically. I need to write the posted data into a MySQL table. The radio buttons names will change as will the qty of buttons.
For example, if four radio buttons are created, the name of each is a variable, $proposed_id (a number), and the values are yes or no.
I wish to have have all of the posted data in one table field. I tried using an array ("props_yes[]") but of course each new one overwrites the previous button.
Thanks for any help.
$sql = "SELECT * FROM table WHERE ballot_name = '$ballot_id' ";
$sql_result = mysql_query($sql,$link);
while ($row = mysql_fetch_array($sql_result))
{
$proposed_id = $row['submission_id'];
echo '<input name="' . $proposed_id . '" id="' . $proposed_id . '_yes"type="radio" value="Yes" required > ';
echo '<label for="' . $proposed_id . '_yes">' . 'YES' . '</label> ';
echo '<input name="' . $proposed_id . '" id="' . $proposed_id . '_no" type="radio" value="No" required > ';
echo '<label for="' . $proposed_id . '_no">' . 'NO' . '</label><br>';
}
While I agree with #trincot that, in general, it is bad practice to store multiple, different kinds of values in a single DB field, there are times that it is called for or even necessary, as for example, when your database uses the EAV pattern as do some popular systems like Wordpress. If this is the primary data that is being stored in your database, you might want to consider a NoSQL database for this project.
That being said, here is how you might handle storing and retrieving your data. First, I would add some key word to the name field of your radio inputs, e.g. name="ballot_'.$proposed_id.'" so that you don't end up with a bunch of fields with numbers as names, and so that you have some way to filter the results on the server side. On the server side then you could do something like (assuming the form was submitted using POST):
// create an associative array of values from your radio buttons
$ballot_values = array();
foreach ($_POST as $index => $value) {
if (false !== strpos($index, 'ballot_')) {
$id = substr($index, 7); // get the numeric part of the name
$ballot_values[$id] = $value;
}
}
Once you do this, $ballot_values will contain an associative array of IDs and yes/no values. In order to save this in a single database field, you need to serialize the array, i.e.
$serialized_ballot_values = serialize($ballot_values);
This will store the array as a single string that you can then store in your DB field. When you retrieve the value from the database, you'll have to unserialize it before you can use it.
Again, if you can avoid doing this, I would. Unfortunately, though, we don't always have control over the structure of the DB so it could be that you have no choice.
Use an array with keys in your radio button names. PHP will interpret the submitted values into an array.
$sql = "SELECT * FROM table WHERE ballot_name = '$ballot_id' ";
$sql_result = mysql_query($sql,$link);
while ($row = mysql_fetch_array($sql_result))
{
$proposed_id = $row['submission_id'];
echo '<input name="props_yes[' . $proposed_id . ']" id="' . $proposed_id . '_yes"type="radio" value="Yes" required > ';
echo '<label for="' . $proposed_id . '_yes">' . 'YES' . '</label> ';
echo '<input name="props_yes[' . $proposed_id . ']" id="' . $proposed_id . '_no" type="radio" value="No" required > ';
echo '<label for="' . $proposed_id . '_no">' . 'NO' . '</label><br>';
}
After the post, the value of $_POST['props_yes'] will contain an array of chosen answers. The keys in the array will be from the $proposed_id
First of all, I am a newbie when it comes to coding, so please be kind and patient :)
What I am trying to do is to select two rows ('ID', 'name') from a MySQL table (categories), populate a drop down list with one row ('name'), and on submission of a form, pass the other ('ID') to another table.
Now, I can populate the drop down list, no problem. I have populated this with both 'ID' and 'name' to test that both of the variables I am using to hold this information, contain the correct data. But I cannot seem to $_POST the information.
I guess I am either looking at the wrong part of the array, or I am simply using the wrong code.
This is the code to create a new product, under a category from the database.
<?php
include 'db_config.php';
?>
<form enctype="multipart/form-data" action="insert.php" method="post">
<h3>Add New Product</h3>
Category:
<!-- START OF categories (table) names (row) SQL QUERY -->
<? $sql = "SELECT ID, name FROM categories";
$result = $mysqli->query($sql);
echo "<select name='category_name'>";
while ($row = $result->fetch_assoc()) {
$cat_ID=$row['ID'];
$cat_name=$row['name'];
extract($row);
echo "<option value='" . $cat_ID . $cat_name . "'>" . $cat_ID . " " . $cat_name ."</option>";
}
echo "</select>";
?>
<!--END OF SQL QUERY -->
<br>
Code: <input type="text" name="code"><br>
Name: <input type="text" name="prod_name"><br>
Description: <input type="textarea" name="description"><br>
Image: <input type="file" name="image"><br>
<input type="Submit">
</form>
For now, I am just echoing this out in the insert.php script, to test the code above. This is a snippet of the insert.php script.
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
echo "Code: ". $_POST['code'] . "<br>";
echo "Name: " . $_POST['prod_name'] . "<br>";
echo "Description: ". $_POST['description'] . "<br>";
echo "Image: " . $_POST['image'] . "<br>";
Don't worry about the last line above. I know this needs to be $_FILES, and I have all this covered. I have stopped writing the data to the table until I get my issue fixed. In the full script, image are being upload to "/images" and the location stored in the table. This all works fine.
The problem is with the first two lines, as they are blank when returned. I thought I was storing the information correctly, as I am calling the same variables to populate the drop down list, but I cannot seem to $_POST it.
Does that makes sense?
Thanks to all who help me. Once day I will be as good as you....I hope.
TIA
Smurf.
this bellow:
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
is wrong, select element has its name category_name, so, instead of this, you should
do:
echo "Category: " . $_POST['category_name'] . "<br>";
echo "ID: " . $_POST['$row["ID"]'] . "<br>";
echo "Category: " . $_POST['$row["name"]'] . "<br>";
There aren't any form elements with those names in your form ($row["ID"] and $row["name"]). Those would be really strange names for a form element anyway. The form element you're creating is:
<select name='category_name'>
So the selected value would be posted as:
$_POST['category_name']
The option elements for that select appear to have values which are a combination of ID and Name:
"<option value='" . $cat_ID . $cat_name . "'>"
Thus, if the user selects an option with a value of 1SomeName then $_POST['category_name'] will evaluate to '1SomeName'.
It's certainly unconventional to use the combination of ID and Name for the option values, but it should work. The problem is presents is that you now have a composite string which needs to be parsed in order to be useful. Generally what one would do is just use the ID as the value and the Name as the display. All you should need to use it throughout the code is the ID.
The $_POST variable you want, is inside category_name
Cuz your select is...
<select name='category_name'>
So you need to get it by...
$_POST['category_name'];
Which will return whatever you've assigned to the select options...ie
2 Name
2 being the ID, and Name being the name
But if you then want to use that ID to retrieve from DB or anything, you're gonna have to explode that apart...like so....to get each piece.
$array = explode(" ", $_POST['category_name']);
That will leave you with...
$array[0] = ID
$array[1] = Name
But I would avoid all that part, by just assigning the ID to the value only...like so..
echo "<option value = '".$cat_ID."'> ".$cat_name." </option>";
That way you just pass the ID and have access to it on the other side.
I have a variable formvar that is incremented every time a user adds an additional field in an HTML form. This variable is posted to the PHP script for the purpose of looping through all of the added fields.
I am trying to combine two variables in the MySQL query to match what is in my HTML form. I would like the MySQL query to go upc0, upc1, etc until the for loop terminates.
for($i=0;$i<=$_POST[formvar];$i++)
{
mysql_select_db("bits", $con);
$sql="INSERT INTO report (UPC, Quantity, Comment)
VALUES ('$_POST[upc].$i','$_POST[quantity].$i','$_POST[comment].$i')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else echo "Records added successfully";
}
Sorry if this code is bad, I am new to web programming.
Thank you!
Ok, since each answer hinted at escaping (but did not give an example):
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . mysql_real_escape_string($_POST["upc".$i]) . "','" .
mysql_real_escape_string($_POST["quantity" . $i]) . "','" .
mysql_real_escape_string($_POST["comment" . $i]) . "')";
That should protect you from SQL Injection, and is one proper method of creating sql queries. The best method would be to use parametrized queries (There's a ton of information out there on it, so I'd suggest a good Google search would be better than me trying to explain it here)...
First things first. In your HTML, create Input-Fields like this:
<input type="foo" name="upc[]">
<input type="foo" name="quantity[]">
<input type="foo" name="comment[]">
Then in your PHP-Script you do it like this:
<?php
# Choose DB
mysql_select_db("bits", $con);
# Iterates the Form-Data
$data_arr = array();
foreach($_POST['upc'] as $k=>$v) {
# Makes sure all needed data is available
if(isset($_POST['quantity'][$k], $_POST['comment'][$k])) {
$data_arr[] = array(
'upc' => $v,
'quantity' => $_POST['quantity'][$k],
'comment' => $_POST['comment'][$k]
);
}
}
# Build mysql insert string
foreach($data_arr as $k=>$v) {
# Escapes each field
$v = array_map('mysql_real_escape_string', $v);
# Maps array to value set
$data_arr[$k] = '('. implode(',', $v). ')';
}
$sql = 'INSERT INTO report (UPC, Quantity, Comment) VALUES '. implode(', ', $data_arr);
# Perform mysql query
mysql_query($sql, $con) or die('Error: ' . mysql_error());
echo 'Records added successfully';
Wrote it on my iPad, i'm on an airplane... so untestet. Good luck. ;o)
Not sure if I understand the question well but this is what I think :
$sql="INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . $_POST["upc".$i] . "','" . $_POST["quantity" . $i] . "','" . $_POST["comment" . $i] . "')";
Note : this is a short version, you must add mysql_real_escape_string, etc, etc.
Also I supposed every variable could be string so I surrounded them by ''.
$_POST["name" . $i] let you loop throught POST variables starting with the name "name" followed by a number, this must be inserted into your for loop.
As recipes are so acclaimed I'm going to give my own, concerning the actual question:
<?php
for ($i=0; $i<=$_POST['formvar']; ++$i) {
mysql_select_db("bits", $con);
$v = array_map(mysql_real_escape_string(array(_POST["upc{$i}"], $_POST["quantity{$i}"], $_POST["comment{$i}"])));
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES('"
. implode("', '", $v)
. "')";
if (!mysql_query($sql,$con)) {
trigger_error(html_entities('Error: ' . mysql_error()));
}
}
?>