I hope this makes sense in relation to the title and what I'm trying to achieve, so here goes...
I have a form that displays between 1 to 30 fields to be entered - the number of fields is determined by the user at a previous stage (it will not always be the same amount).
If a user has 5 fields to fill out, they must all contain data - the same if they set 15 fields or 30 fields.
What I want to be able to do is loop through the POST variables in the form, make sure they are all set and either insert the data to the database, or display an error.
I was going to do 30 if statements with nested if statements:
if ($numberOfFields == 1){
if (!$_POST["field1_text"]){$error = 1;}
};
if ($numberOfFields == 2){
if (!$_POST["field1_text"]){$error = 1;}
if (!$_POST["field2_text"]){$error = 1;}
};
But this seems a very long winded way and I was wondering if anyone had any suggestions or pointers.
I was wondering if something like this would work:
for ($q = 1; $q <= $numberOfFields; $q ++){
if (!$_POST["field'".$q."'_text"]){
$error = 1;
}
}
But I'm getting an error referencing the variable/field name using the $q. Should this be [$q] or something else?
I'm struggling to find any answers, but probably not asking the right question, but any help would be appreciated.
Thanks
It could be done like this, using a foreach instead of a for:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$error = false;
foreach($_POST as $key => $value)
{
if(strpos($key, 'field') === 0)
{
if($value == '')
{
$error = true;
break;
}
}
}
if($error)
{
// not all fields have a value - show message
}
}
It would be much easier if you used an input array on the form, instead of manually populating the input names with a number concatenated. Example:
<input type="text" name="field[]" />
<input type="text" name="field[]" />
<input type="text" name="field[]" />
On the PHP side, simply loop over them:
foreach($_POST['field'] as $field)
{
if($field == '')
{
// error - doesn't have a value
}
}
Use this:
for ($q = 1; $q <= $numberOfFields; $q++){
if (!$_POST["field".$q."_text"]){
$error = 1;
}
}
In your own code you had weird extra '
Related
The input record includes fifteen fields named 'student01', 'student02', student03' ... 'student15'. I need to do the same thing with the value stored in each of the fields. There's got to be a better way than:
if ($student01 != '') {
// process the info in $student01
}
if ($student02 != '') {
// process the info in $student02
}
...
if ($student15 != '') {
// process the info in $student15
}
I was thinking that PHP's variable variables might be the solution, but haven't figured out the right syntax.
Help appreciated.
Thanks!
Change the number 3 in the for statement to be 1 more than the number of students you are going to have.
for ($snum = 1;$snum < 3;$snum++) {
#echo ${'student' . str_pad($snum,2,'0',STR_PAD_LEFT)}; // left to show it works
if (${'student' . str_pad($snum,2,'0',STR_PAD_LEFT)} != '') {
echo 'Do something';
}
}
i would like to ask for your help to solve my problem. Your help is kindly appreciated.
My question is i have two inputs type which are array ( <input type='text' name='cost[]'> and <input type='text' name='price[]'> ) in view. Both inputs type are within a foreach statement. Let's say foreach from a table of database that has 3 records. So, from the view of web browser it requires user to input 3 times on the cost and price fields for every record. In my controller, i want to compare user input as below
-price[1] cannot be more than cost[1]
-price[2] cannot be more than cost[2]
-price[3] cannot be more than cost[3]
by using if else statement. How am i going to code in my controller so that price[1] is only compared to cost[1], price[2] is only compared to cost[2] and price[3] is only compared to cost[3].Below is my code in my controller, but cannot work.
$cost = $this->input->post('cost');
$price = $this->input->post('price');
if ($price > $cost)
{
echo "Rejected";
}
else
{
echo "Accepted";
}
You will need to loop over all the values.
My Codeigniter is a little rusty but I believe $cost and $price should both be arrays. Some something simple like this;
foreach ($price as $key => $value) {
if ($value > $cost[$key] ) {
echo "Rejected";
} else {
echo "Accepted";
}
}
If you want all to be valid then you could just break on the first rejected value. Otherwise you loop through all and warn the user about the invalid ones?
Please try the code below.
For demo: Demo URL
<?php
//$cost = $this->input->post('cost');
//$price = $this->input->post('price');
//Suppose I have added dummy values in these variable as you received from view.
$cost = array(1,2,3);
$price = array(3,4,1);
//as you mentioned each one cost have price like $cost zero index compared with $price zero index.
$i = 0;
foreach($cost as $cos){
if ($price[$i] > $cos)
{
echo "Rejected";
}
else
{
echo "Accepted";
}
$i++;
}
?>
I have a problem in trying to store database values in their respective rows inside the database using dynamic form fields. I have provided here the screenshots of my codes and outputs.
This is my script in adding dynamic form fields in which the form is located in a separate file named load_work_experience_form.php
This is the html code for the form I have appended in the my script to add a dynamic form fields
This is the look of my dynamic form fields
This happens to be the wrong output inside the database in which data values do not store in their proper record. I am attempting to insert 2 records of work experience but it seems that it has created 4 records.
The source code for adding into the database is supplied below. Kindly help me in fixing this problem. Thanks. More power:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
foreach ( $_POST['employer'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (employer) VALUES ('$values')");
}}
if (isset($_POST['job_position'])) {
foreach ( $_POST['job_position'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (job_position) VALUES ('$values')");
}}
//some more codes here for Work From and To. This website does not accept alot of codes. But the codes here are just like the ones at the top.
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
In the case that you have every time the same fields with dynamic rows:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
for ($i = 0, $nCount = count($_POST['employer']); $i < $nCount; $i++) {
$employer = mysql_real_escape_string($_POST['employer'][$i]);
$job_position = mysql_real_escape_string($_POST['job_position'][$i]);
$query = mysql_query('INSERT INTO tbl_work_exp (´employer´, ´job_position´) VALUES (´' . $employer . '´, ´' . $job_position . '´)');
}
}
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
You must add there the other fields also...
The problem of your logic is that you do for every field a insert but you need only one insert for one row.
And please don't use mysql library in php, it is better to use mysqli
Your problem is that you pass each value separately. I strongly suggest to change your HTML markup to group each value, but that's not the goal here. As for your current problem, this is a quick solution that can help you through. Picking up from your current code:
<?php
if (isset($_POST['update_profile'])) {
$profileFields = array('employer', 'job_position');
$profiles = array();
foreach ($profileFields as $field)
{
if (isset($_POST[$field])) {
foreach ($_POST[$field] as $key => $value) {
if (!isset($profiles[$key])) {
$profiles[$key] = array();
}
$profiles[$key][$field] = mysql_real_escape_string($value);
}
}
}
foreach ($profiles as $profile) {
$tableCols = implode(",", array_keys($profile));
$profileValues = implode("','", array_values($profile));
$insertQuery = "INSERT INTO tbl_work_exp ({$tableCols}) VALUES ('{$profileValues}')";
}
}
?>
Give or take a few tweaks or special treatment for each field. This is very generic code just to give you a guide.
Hope this helps
<?php
if(isset($_POST['Button_name'])){
for($i=0; $i<count($_POST['employer_name']); $i++){
$query="INSERT INTO table_name(employer_name,employer_age) VALUES ('".$_POST['employer_name']."','".$_POST['employer_age']."')";
$result=mysql_query($query);}}
<?php
$count_post_value = $_POST['first_name'] //this is value of text box //
for($i=0; $i<$count_post_value; $i++)
{
if(trim($_POST["first_name"][$i] && $_POST["last_name"] && $_POST["remarks"]!= ''))
{
$sql = mysql_query("INSERT INTO Table_name(first_name,last_name) VALUES('".$_POST["first_name"][$i]."','".$_POST["last_name"][$i]."')");
if($sql)
{
echo "<script>alert('Inserted Successfully');</script>";
}
else
{
echo "<script>alert('ERROR');</script>";
}
}
}
?>
I thought I would edit my question as by the comment it seems this is a very insecure way of doing what I am trying to acheive.
What I want to do is allow the user to import a .csv file but I want them to be able to set the fields they import.
Is there a way of doing this apart from the way I tried to demonstrate in my original question?
Thank you
Daniel
This problem I am having has been driving me mad for weeks now, everything I try that to me should work fails.
Basically I have a database with a bunch of fields in.
In one of my pages I have the following code
$result = mysql_query("SHOW FIELDS FROM my_database.products");
while ($row = mysql_fetch_array($result)) {
$field = $row['Field'];
if ($field == 'product_id' || $field == 'product_name' || $field == 'product_description' || $field == 'product_slug' || $field == 'product_layout') {
} else {
echo '<label class="label_small">'.$field.'</label>
<input type="text" name="'.$field.'" id="input_text_small" />';
}
}
This then echos a list of fields that have the label of the database fields and also includes the database field in the name of the text box.
I then post the results with the following code
$result = mysql_query("SHOW FIELDS FROM affilifeed_1000.products");
$i = 0;
while ($row = mysql_fetch_array($result)) {
$field = $row['Field'];
if ($field == 'product_name' || $field == 'product_description' || $field == 'product_slug' || $field == 'product_layout') {
} else {
$input_field = $field;
$output_field = mysql_real_escape_string($_POST[''.$field.'']);
}
if ($errorcount == 0) {
$insert = "INSERT INTO my_database.products ($input_field)
VALUES ('$output_field')";
$result_insert = mysql_query($insert) or die ("<br>Error in database<b> ".mysql_error()."</b><br>$result_insert");
}
}
if ($result_insert) {
echo '<div class="notification_success">Well done you have sucessfully created your product, you can view it by clicking here</div>';
} else {
echo '<div class="notification_fail">There was a problem creating your product, please try again later...</div>';
}
It posts sucessfully but the problem is that it creates a new "row" for every insert.
For example in row 1 it will post the first value and then the rest will be empty, in row 2 it will post the second value but the rest will be empty, row 3 the third value and so on...
I have tried many many many things to get this working and have researched the foreach loop which I haven't been familiar with before, binding the variable, imploding, exploding but none of them seem to do the trick.
I can kind of understand why it is doing it as it is wrapped in the while loop but if I put it outside of this it only inserts the last value.
Can anyone shed any light as to why this is happening?
If you need any more info please let me know.
Thank you
Daniel
You're treating each field you're displaying as its own record to be inserted. Since you're trying to create a SINGLE record with MULTIPLE fields, you need to build the query dynamically, e.g.
foreach ($_POST as $key => $value);
$fields[] = mysql_real_escape_string($key);
$values[] = "'" . msyql_real_escape_string($value) . "'";
} // build arrays of the form's field/value pairs
$field_str = implode(',', $fields); // turn those arrays into comma-separated strings
$values_str = implode(',', $values);
$sql = "INSERT INTO yourtable ($field_str) VALUES ($value_str);"
// insert those strings into the query
$result = mysql_query($sql) or die(mysql_error());
which will give you
INSERT INTO youtable (field1, field2, ...) VALUES ('value1', 'value2', ...)
Note that I'm using the mysql library here, but you should avoid it. It's deprecated and obsolete. Consider switching to PDO or mysqli before you build any more code that could be totally useless in short order.
On a security basis, you should not be passing the field values directly through the database. Consider the case where you might be doing a user permissions management system. You probably wouldn't want to expose a "is_superuser" field, but your form would allow anyone to give themselves superuser privileges by hacking up their html form and putting a new field saying is_superuser=yes.
This kind of code is downright dangerous, and you should not be using it in a production system, no matter how much sql injection protect you build into it.
Alright....I can't say that I know exactly whats going on but lets try this...
First off....
$result = mysql_query("SHOW FIELDS FROM my_database.products");
$hideArray = array("product_id","product_name","product_description", "product_slug","product_layout");
while ($row = mysql_fetch_array($result)) {
if (!in_array($row['Field'], $hideArray)){
echo '<label class="label_small">'.$field.'</label>
<input type="text" name="'.$field.'" id="input_text_small" />';
}
}
Now, why you would want to post this data makes not sense to me but I am going to ignore that.....whats really strange is you aren't even using the post data...maybe I'm not getting something....I would recommend using a db wrapper class...that way you can just through the post var into....ie. $db->insert($_POST) ....but if you ware doing it long way...
$fields = "";
$values = "";
$query = "INSERT INTO table ";
foreach ($_POST as $key => $data){
$values .= $data.",";
$fields .= $fields.",";
}
substr($values, 0, -1);
substr($fields, 0, -1);
$query .= "(".$fields.") VALUES (".$values.");";
This is untested....you can also look into http://php.net/manual/en/function.implode.php so you don't have to do the loop.
Basically you don't seem to understand what is going on in your script...if you echo the sql statements and you can a better idea of whats going....learn what is happening with your code and then try to understand what the correct approach is. Don't just copy and paste my code.
I have the following to generate a state drop down on a form:
$states = array('State', 'Alabama', 'Alaska', 'Arizona', 'Arkansas');
echo "<select name='choose_state'>\n";
foreach ($states as $key => $state)
{echo "<option value='$key'>$state</option>\n";}
echo "</select>";
How would I go about making sure a user
1) only selects one of the options in the array
2) doesn't select the default value? ([0]=> string(5) "State")
edit: validate in php, this is for a form collecting user information before posting to a db
I tried using in_array and got stuck trying to exclude the default value
I think you're missing some checks. You should never rely on what is exacly posted, and always perform thorough checking:
$chosen_state = null;
if (array_key_exists('choose_state', $_POST))
{
$choose_state = $_POST['choose_state'];
if (array_key_exists($choose_state, $states) && $choose_state > 0)
{
// Value does actually exist in array and is not item 0.
$chosen_state = $states[$chose_state]);
}
}
Following example assumes that you're storing the key provided for the select in the var $state_key...
try this:
$max = sizeof($states) - 1; // this is the number of possible values that you have, minus the default
if($state_key != 0 && $state_key > 0 && $state_key < $max)
{
// do whatever here, you've got good data at this point
}
This also assumes that your default value is always key #0 (first in the array), by the way.
Validating form submit in php:
When you submit form in php, Select input type returns selected value in post. So you can do something like:
$selectedindex = $_POST["choose_state"];
if($selectedindex == 0)
{
echo "Default item has been selected";
}
else{
echo "Other than default item has been selected ";
//you can do further validation here for selected item
//is in between 0 and 5 if you need to do so
}