I am having a hard time wrapping my head around the foreach construct. I have found numerous examples of course, but I never seem to be able to adapt them to my needs.
Please consider this working example I have:
I am collecting two dates in an HTML form:
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" name="FirstAGMDate" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" name="MinutesInspectedFromDate" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
On submit the values are being pushed to the mysql database with a PDO prepared statement:
if (isset($_POST['submit'])) {
$sql = "UPDATE jobsinglevalues SET Date = :FirstAGMDate WHERE FormId = 0;
UPDATE jobsinglevalues SET Date = :MinutesInspectedFromDate WHERE FormId = 1;";
$sth = $db->prepare($sql);
$sth->execute(array(':FirstAGMDate'=>($_POST['FirstAGMDate']), ':MinutesInspectedFromDate'=>($_POST['MinutesInspectedFromDate'])));
}
This works no problem, but it's not very clever when I need to repeat this for a dozen inputs. What I want to do is achieve this with only one line of sql; looping for each <input type="text" name="Value" />.
How can I place this into a foreach loop?
In my head it works like this:
On submit each input updates the value in the database based on FormId, which increments by 1 each loop starting at 0. FormId is not a primary key, it simply mirrors the order in which the form elements are displayed.
Update - working example
if (isset($_POST['submit'])) {
$FormId = 0;
foreach($_POST['Value'] as $avalue){
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId";
$sth = $db->prepare($sql);
$sth->execute(array(':Value'=>($avalue), ':FormId'=>($FormId)));
++$FormId;
}
}
This seems to logically work to me! Is the correct solution similar? Please let me know if I need to clarify anything.
Thankyou,
Sam
Let's start by making sure all our values are in an array after posted; if you don't care about the keys you can just use name="Values[]", but I'll use name="Value[FirstAGMDate]" etc so we know what key a value belongs to.
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" id="FirstAGMDate" name="Value[FirstAGMDate]" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" id="MinutesInspectedFromDate" name="Value[MinutesInspectedFromDate]" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
Now we can process the posted array of values. If we want to do something with the key, we can use foreach($_POST['Value'] as $akey => $avalue), if we are only interested in the values then foreach($_POST['Value'] as $avalue) suffices.
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId;";
$sth = $db->prepare($sql);
foreach($_POST['Value'] as $akey => $avalue) {
$sth->execute(array(':Value' => $avalue, ':FormId'=> $FormId ));
++$FormId;
}
[edit] As per edit-suggestion by #AravindKishore, creating the prepared statement is better done before the loop. Prepare once, enjoy forever.
Related
I am setting up a system that has many answers from a question. Therefore the user can click a button to dynamically add answers. I want the user to be able to tick a checkbox next to the answers which are correct and then insert this into the database (1 being correct).
Here is what I have:
HTML:
<div id="answers">
<label class="answer">
Answer:
<input type="text" name="ab_name[]" value=""/>
Correct?
<input type="checkbox" name="ab_correct[]" value="0">
</label>
</div>
PHP
$ab_name = $_POST['ab_name'];
$ab_correct = $_POST['ab_correct'];
$sql = "INSERT INTO answers_bank (`ab_name`, `ab_correct` ) VALUES (:ab_name, :ab_correct )";
$stmt = $db->prepare($sql);
foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $ab_correct);
$stmt->execute();
}
Like this:
The SQL inserts the ab_name but the ab_correct is ALWAYS set to 1 if it is ticked or unticked. Any guidance on this please?
You could use a for loop instead of the foreach. Well, first of all, you need to make sure both arrays has the same amount of elements.
if(count($_POST['ab_name']) != count($_POST['ab_correct']))
exit('Not same amount of elements.');
Then, loop through each of them.
for($i=0; $i<count($_POST['ab_name']); $i++){
$stmt->bindValue(':ab_name', $_POST['ab_name'][$i]);
$stmt->bindValue(':ab_correct', $_POST['ab_correct'][$i]);
$stmt->execute();
}
if(isset($_POST['$ab_correct'])){$update = 1;}else{$update = 0;}
foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $update);
$stmt->execute();
}
Is it possible to POST checkbox name even if its not checked?
<input type='checkbox' class='tinyField' name='alert_by_email' value="1" <?PHP echo $alert_by_emailChecked ?> />
foreach ($_POST AS $field => $value)
$sql[] = $field." = '". $value."'";
$sql = implode(' , ',$sql);
$query = "UPDATE user_setup SET ".$sql." WHERE (userID = ".$userID.") " ;
$res = mysql_query($query);
So when I PRINT_R the POST i will get the field, but it will be empty
Array ( [alert_by_email] => '' )
Add this before your checkbox.
<input type='hidden' name='alert_by_email' value="" />
The straight forward answer is no.
The HTML form wont send the checkbox if it's not checked.
However, there are some workarounds:
use js to Generate a hidden input for each checkbox you have, set the value to 0 or '', and whenever you check them, remove the hidden input.
you could simply test if the key exist in the post like so:
if (isset($_POST['alert_by_email']))
In Short, No this is not possible if you are posting FORM without using any Javascript.
Also, Your code may be injected easily as you are relying on user provided column names without validating those. I am posting alternative way to do that. Hope that helps:
Suppose you have this HTML Form:
<form method="POST">
First name:<br />
<input type="text" name="firstname" />
<br />
Last name:<br />
<input type="text" name="lastname" /><br />
<input type="submit" />
</form>
Now, if you want to update values using PHP, your code should be:
<?php
$columnArray = array('firstname' => NULL, 'lastname' => NULL); // This is list of columns which can be updated using form input values (NULL is default value here)
$submittedValues = array_intersect_key($_POST, $columnArray);
// Above code will produce an array like `array('firstname' => 'anyname', 'lastname' => 'anylastname')
//--> Now you can generate your SQL using `$submittedValues`
$sql = array();
foreach ($submittedValues as $field => $value)
{
$sql[] = $field." = '". $value."'";
}
$sqlString = implode(' , ',$sql);
Using this way, hacker will not be able to add extra columns which shouldn't be updated by user i.e. last_login_date or something.
i have this two text fields that ask the user to put in two numbers that are limited to 49 numbers, so that i can have an array of number 1 to 50, or 151 to 200, or 27551 to 27600 any number but a series of 49 consecutive numbers, my problem is i dont know how to put them inside the database, i have no clue i have been searching for everything about inserting arrays but they dont work on my case,
This is my form
<form id="form3" name="form1" method="post" action="">
<p>From:
<input type="text" name="from" id="form_number" class="from" />
- To:
<input type="text" name="to" id="form_number" class="to" />
</p>
<p>Waybill Booklet:
<select name="waybill_booklet[]" id="form_list">
<?php
do {
?>
<option value="<?php echo $row_Booklet['id_waybill_booklet']?>"><?php echo $row_Booklet['booklet_no']?></option>
<?php
} while ($row_Booklet = mysql_fetch_assoc($Booklet));
$rows = mysql_num_rows($Booklet);
if($rows > 0) {
mysql_data_seek($Booklet, 0);
$row_Booklet = mysql_fetch_assoc($Booklet);
}
?>
</select>
</p>
<p>
<input type="hidden" name="status[]" value="4" />
<input type="submit" name="button" id="form_button" value="OK!" />
</p>
</form>
the 49 series of consecutive numbers will be inserted into the database with a foreign key what is chosen from the drop down menu, and a value of 4 that is in the hidden field, so basically there are 4 columns to my table 1 for primary key 1 for the series of numbers and 1 for the foreign key and the last will be the value of the numbers.
This is my php code to get the series of numbers
<?php
$booklet = $_POST['waybill_booklet'];
$status = $_POST['status'];
$from = $_POST['from'];
$to = $_POST['to'];
$number = range($from,$to);
$count = 0;
$myArray = range($from,$to);
while($count<=49){
if($count<49){
echo $myArray[$count]. ", ";
}else{
echo $myArray[$count];
}
$count++;
}
?>
i dont know how to insert the data's
$waybill = mysql_real_escape_string($_POST['waybill_booklet'][0]);
$status = mysql_real_escape_string($_POST['status'][0]);
foreach (range($from, $to) as $number) {
$sql = "INSERT INTO yourTable (id, waybill, status) VALUES($number, '$waybill', '$status')");
mysql_query($sql) or die(mysql_error());
}
You should also switch to PDO or mysqli, so you can use parametrized queries instead of substituting strings into the query. Then you don't need to escape the values like that.
Instead of storing this as an array (since you want to store this as bulk, I assume it will not involve any direct database level aggregation or computation), you can store it as a json string using the json_encode($myArray_series_of_numbers). This gives you the flexibility to store them as a string column and when you retrieve it back, you can use json_decode($model->series_of_numbers_column,true) to get it back as an array for easy computation back in PHP.
Hope this helps
Here is a tutorial on using mysql in php http://www.w3schools.com/php/php_mysql_insert.asp specifically the INSERT command. just build your data into variables instead of echo'ing it and then follow the guide to interact with a database
here is the auto increment tutorial to generate primary ids for each array element http://www.w3schools.com/sql/sql_autoincrement.asp
you can greatly increase the speed of the inserts and do it in one submit by building a multiple insert sql string.. and then using the insert guide above to run it.
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
sorry for my confusing question.
let me rephrase the details:
$query = "SELECT * FROM table";
sample data:
Item Name: Quantity:
Coke 2
Pepsi 3
Gatorade 4
<form action="exec.php" method="POST">
<input type="hidden" name="item_name" value="<?php for each loop goes here?/>"
<input type="hidden" name="quantity" value="<?php for each loop goes here?/>"
<input type="submit" name="submit"/>
</form>
Now, in my exec.php page.
if(isset($_POST['submit'])){
$item_code =$_POST['item_code'];
$quantity =$_POST['quantity'];
$test= explode('\n',$item_code);
$test2 = explode('\t',$quantity);
this part is where my problem is..
here is my update query:
foreach($item as $test){
$update = "UPDATE table SET quantity='$quantity' WHERE item_code='$item_code'"
}
}
as you can see, $quantity will be left out, since it would also need to be looped to match the $item_code.
or is there any better way to do this?
im quite new to php, so please pardon me if im doing it wrong the way..
I dont understand, do you have an issue reading the data from MySQL? do you have an issue updating the data to MySQL? In any case it seems that you are refering a SQL issue rather than an HTML or PHP, can you post your SQL script?
Hi I am trying to build a form with checkboxes and upon submitting the form, I want to see which checkboxes were checked and update the database accordingly. How is this done? I've tried so many different code and none of them worked. The closest I've gotten was to update only the checked ones. I also need to update the database if they are unchecked as well like a toggle.
So far my code is like this for the form
<form action="" method="post">
<input type=checkbox" value="<?php echo member['id']; ?>" name="member[]" />
<input type="submit" name="update" value="Update" />
</form>
And for the PHP loop I have (excerpt)
foreach ((array)$_POST['test'] as $member) :
$sql = "UPDATE `sp_members` SET `allow_test` = '1' WHERE `id` = '$member'";
Since I think the loop only picks up the checkboxes that are checked, it doesn't pick up the ones that were orignally checked and now unchecked...
Any help appreciated!
Simply update everything instead of trying to figure out what changed - if you programmed it yourself, you would have to make your code a lot more complicated, and as the database is already optimized for speed, it's better to just stuff it in the DB and let it handle it.
You could use a ternary operator to set the correct value.
$sql = "UPDATE `sp_members` SET `allow_test` = '"
. ( $_REQUEST['checkbox'] ? 1 : 0 )
. "' WHERE `id` = '" . mysql_real_escape_string( $member ) . "'";
It checks $_REQUEST['checkbox'] for a non-null, non-zero string and if true, returns 1, if false, returns 0.
(($_post['member']) ?$allow_test = 1 : $allow_test = 0;
$sql = "UPDATE `sp_members` SET `allow_test` = $allow_test WHERE `id` = '$member'";
The reason why this hasn't been working (and won't in the already provided answers) is because checkboxes that are not checked won't exist in the $_POST/$_REQUEST arrays. The other side of that is if they do exist, they must be true.
When you're doing the check to see what the value is, you are causing an error because the key to the array doesn't exist.
Instead, you need to know the available checkboxes and then check if each isset() in the array.
Webform:
<form action="foo.php" method="post">
<input type="checkbox" value="<?php echo $value1; ?>" name="checkbox1" />
<input type="checkbox" value="<?php echo $value2; ?>" name="checkbox2" />
<input type="submit" name="update" value="Update" />
</form>
PHP:
$checkboxes = array(
'column1' => 'checkbox1',
'column2' => 'checkbox2',
);
foreach ($checkboxes as $column => $checkbox)
{
$value = (isset($_POST[$checkbox]) ? 1 : 0);
$sql = "UPDATE `table` SET `$column` = '$value' WHERE `id` = '$member'";
}
When confronted with this, I usually punt and rely on a transaction to update this stuff for me. As you've discovered, unchecked checkboxes won't get submitted with the form, so you'd have to do tedious comparisons to figure out what's changed each time and build up an appropriate update and/or delete query sequence.
Instead, I fire up a transaction, delete all the old checkbox values stored in the DB, and then insert the new ones submitted with this request. Unless you've got the checkboxes acting as foreign keys and/or triggers set on them at the DB level, this is a relatively lightweight option and saves you the trouble of having to compare the old and new lists for changes.