I'm creating (and deleting) input fields dynamically in jQuery so they looks like:
<div id="new">
<div>
<input type="text" name="title1" value="" />
<input type="text" name="desc1" value="" />
</div>
<div>
<input type="text" name="title4" value="" />
<input type="text" name="desc4" value="" />
</div>
<div>
<input type="text" name="title7" value="" />
<input type="text" name="desc7" value="" />
</div>
</div>
As you can see, my fields names are not always like: 1,2,3 but they're sometimes like 1,4,7.
My php code (part) to insert row into db table:
$i = 0;
global $wpdb;
$table_name = $wpdb->prefix . 'plugin';
$wpdb->insert( $table_name, array( 'title' => $_POST['title'], 'desc' => $_POST['desc'] ) );
jQuery:
var count = <?php echo $i; ?>;
$("#addnewbutton").click(function() {
count = count + 1;
$('#new').append('<div><input type="text" name="title'+count+'" value="" /><input type="text" name="desc'+count+'" value="" /></div>');
});
I know that I need to use "for" loop (probably) but I don't know how to do it and I don't want to add empty rows.
Regards
Taking a purely PHP approach, you can run a loop through $_POST and check if the keys begin with 'title', split the string into two parts: the 'title' and the {number}. Check if a key with 'desc{number}' exists, if it does...you know what to do.
You can also process the form with JavaScript/JQuery first so it's really nice when PHP gets it by a JSON that has a 'title' obj and a 'desc' obj.
Related
I have a custom WordPress page template where I wrote a basic form structure like this:
<div class="my-form">
<h2>WILL YOU ATTEND?</h2>
<form action="#" autocomplete="off" method="POST">
<input class="input" type="text" spellcheck="false" name="name" placeholder="Name" required>
<input class="input" type="email" spellcheck="false" name="email" placeholder="E-mail" required>
<label class="ans">Yes
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<label class="ans">No
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<button> SUBMIT </button>
</form>
</div>
Now once the submit button is clicked, I'm trying to figure out how to create a table in WordPress database, and insert the form data into it using $wpdb.
PS: I left the action attribute empty because I don't know how to go about this exactly.
There are several ways to do that. Below I just showed you one way:
I Assume your table name is wp_customform which has id, name, email, and radio columns.
Now you've to modify your HTML code like the below. I added some JS too.
<div class="my-form">
<h2>WILL YOU ATTEND?</h2>
<form class="custom-form-class" action="#" autocomplete="off" method="POST">
<!-- Action is here but hidden. This will be use in php side -->
<input type="hidden" name="action" value="sample_custom_form_action">
<input class="input" type="text" spellcheck="false" name="name" placeholder="Name" required>
<input class="input" type="email" spellcheck="false" name="email" placeholder="E-mail" required>
<label class="ans">Yes
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<label class="ans">No
<input type="radio" name="radio">
<span class="checkmark"></span>
</label>
<button> SUBMIT </button>
</form>
</div>
<script>
// Javascript to send ajax request
jQuery(document).on('submit', '.custom-form-class', function(e){
let formData = jQuery(this).serialize();
// Change ajax url value to your domain
let ajaxurl = 'http://YOURSITE.COM/wp-admin/admin-ajax.php';
// Send ajax
jQuery.post(ajaxurl, formData, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
That pieces of code will send your form data to the PHP side. You have to use the below code to process the form data in your function.php file.
add_action( 'wp_ajax_sample_custom_form_action', 'prefix_save_custom_form_data' );
add_action( 'wp_ajax_nopriv_sample_custom_form_action', 'prefix_save_custom_form_data' );
function prefix_save_custom_form_data(){
global $wpdb;
// Get the values
$name = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : ''; // Empty value if data not set
$email = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : ''; // Empty value if data not set
$radio = isset( $_POST['radio'] ) ? sanitize_text_field( $_POST['radio'] ) : ''; // Empty value if data not set
// Assume your table name is wp_customform
$your_table_name = $wpdb->prefix . 'customform';
// Insert into database
$wpdb->insert(
$your_table_name,
array(
'name' => $name,
'email' => $email,
'radio' => $radio,
)
);
// Send insert id as ajax response
echo $wpdb->insert_id;
// Use die to stop the ajax action
wp_die();
}
The codes are not tested but they should work. I am attaching some reference links below:
Ajax overview: https://codex.wordpress.org/AJAX_in_Plugins
For Insert: https://developer.wordpress.org/reference/classes/wpdb/insert/
For create table: https://developer.wordpress.org/reference/functions/dbdelta/
I got this 2 array in a form to be process. However, i only manage to get the output from only one of the array. Sample as below :
<inputs id="location" type="text" name="data[]" value=""/>
<input id="shipval" type="text" name="data[][id]" value=""/>
And in the PHP part is below :
foreach ($_POST ["data"] as $id => $subs) {
foreach ($subs as $key=>$sub) {
$subcategory = $sub;
if($subs['id']=="$subcategory"){
echo $sql = " insert into x(kodLebuhraya,kodSeksyen) values ('".$subs['id']."','".$sub."')";echo "<br>";
}else{
//echo "hi2";
echo $sql = " insert into x(kodLebuhraya,kodSeksyen) values ('".$subs['id']."','".$sub."')";echo "<br>";
}
}
}
It means one location for one shipval. i have multiple input field for location and shipval. Can you guys enlight me which one is wrong. Thanks in advanced.
So basically you need to pass location and shipval in pairs.
Try this structure in HTML:
<label>Set One</label>
<input class="location" type="text" name="data[location][]" value=""/>
<input class="shipval" type="text" name="data[shipval][]" value=""/>
<label>Set Two</label>
<input class="location" type="text" name="data[location][]" value=""/>
<input class="shipval" type="text" name="data[shipval][]" value=""/>
<label>Set Three</label>
<input class="location" type="text" name="data[location][]" value=""/>
<input class="shipval" type="text" name="data[shipval][]" value=""/>
And this code for PHP:
foreach ($_POST['data']['location'] as $key => $location) {
$shipVal = $_POST['data']['shipval'][$key];
//now you have a pair of $location and $shipVal
echo $location.' : '.$shipVal.'<hr>';
}
Avoid using named indexes after unnamed ones ex. <input name="array[][named]" /> you can lose order of fields if one of pair fields is empty.
You have <inputs id="location" instead of <input id="location"
Also... foreach ($subs as $key => $sub) { will throw an error for <inputs id="location" type="text" name="data[]" value=""/> because it is not multidimensional. So try changing that to <inputs id="location" type="text" name="data[][]" value=""/>
For multiple select, the name has to end in square brackets, so you'll need to change the name of your shipval inputs
Firstly you have writtten inputs instead of input.
Secondly, this line:
foreach ($subs as $key=>$sub) {
will treat each variable as an array, but the location isn't an array.
I did not see the need for a loop since you want to just access $_POST['data'][0] and $_POST['data'][1]['id']
I also noticed that your SQL is a duplicate so you can try You can try
$sql = "INSERT INTO x(`kodLebuhraya`,`kodSeksyen`) VALUES ('%s','%s')" ;
printf($sql,mysqli_real_escape_string($_POST['data'][0]),mysqli_real_escape_string($_POST['data'][1]['id']));
Output
INSERT INTO x(`kodLebuhraya`,`kodSeksyen`) VALUES ('A','B')
Form Used
<form method="POST">
A : <input id="location" type="text" name="data[]" value="" />
B : <input id="shipval" type="text" name="data[][id]" value="" />
<input id="shipval" type="submit" name="submit" value="Submit" />
</form>
I am in a fix here. I have code that does not insert multiple data into mysql table with one form. Here's my code-
<?php
if (isset($_POST['submitted'])) {
include('config.php');
foreach($_POST['name'] as $row=>$nam) {
$name=$nam;
$class=$_POST['class'][$row];
echo "<br/>" . $name . "<br/>" . $class;
$sql="INSERT INTO multiple (name, class) VALUES ('$name','$class')";
}
if (!mysql_query($sql)) die('Error: ' . mysql_error());
echo "1 record added";
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label>Name1:
<input id="name" name="name[]" type="text">
<input type="hidden" name="submitted" value="true" />
</label>
<label> Class1:
<input id="class" name="class[]" type="text">
</label>
<label>Name2:
<input id="name" name="name[]" type="text">
</label>
<label>Class2:
<input id="class" name="class[]" type="text">
</label>
<label>Name3:
<input id="name" name="name[]" type="text">
</label>
<label>Class3:
<input id="class" name="class[]" type="text">
</label>
<label>Name4:
<input id="name" name="name[]" type="text">
</label>
<label>Class4:
<input id="class" name="class[]" type="text">
</label>
<label>Name5:
<input id="name" name="name[]" type="text">
</label>
<label>Class5:
<input id="class" name="class[]" type="text">
</label>
<input value="Add" type="submit">
</form>
When I press the submit button nothing inserts in the mysql table. Only empty fields are created. If I insert 5 text field I get 5 empty fields in sql table.
Imroz, your use of [] as part of the names of your input elements (not id's) example name="class[]" when the form is posted it builds an array. The post object PHP would recognize would be $_POST['class']
But that being an array means you have to handle it slightly different before inserting it into your database as you can't just (well maybe you can) drop an array into the DB
if you did
for($x=0;$x < count($_POST['class']); $x++)
{
echo $_POST['class'][$x].'<br>';
}
you would be able to see all your posted inputs from the inputs with the name class[]
of course this is a core example of what you need to do overall, but I am just trying to express whats going on with your posted data.
i think your inserting query is problem.....try like this
$query = mysql_query("INSERT INTO category VALUES('','$name','$class','')") or die(mysql_error());
You have the } in the wrong place.
The } right after the $sql= should be moved after the echo "1 record added";
I reformatting your code to use proper indenting and the error was obvious.
I have a form that looks like so:
<label for="fullpath"><span class="required">*Full Path of folder to change access:</span></label>
<input name="fullpath" id="it10" type="text" size="50" maxlength="50" />
<br />
<small>Example: g:\A\Folder or j:\Your\Folder</small><br />
<div class="bgdiff">
<label for="userpermissiongroup">User Permission Group to be changed:</label>
<input name="userpermissiongroup" type="text" id="it11" size="50" maxlength="50" />
<small>If Known...</small></div>
<br />
<label for="addreadaccess">Additional users requiring read access:</label>
<input name="addreadaccess" type="text" id="it12" size="15" maxlength="15" />
<br />
<small>AD Username</small><br />
<div class="bgdiff">
<label for="addauthoraccess">Additional users requiring author access:</label>
<input name="addauthoraccess" type="text" id="it13" size="12" maxlength="12" />
<br />
<small>AD Username</small></div>
<br />
<label for="removeaccess">Users to be removed from access:</label>
<input name="removeaccess" type="text" id="it14" size="12" maxlength="12" />
<br />
<small>AD Username</small><br />
<div class="bgdiff">
<label for="supervisor"><span class="required">*Data Steward, Program Manager, Project Lead, or Supervisor who can authorize access changes:</span></label>
<input name="supervisor" type="text" id="it15" size="30" maxlength="30" />
<br />
<small>AD Username</small></div>
<br/>
<label for="phoneapprover"><span class="required">*Phone number of approving official: </span></label>
<input name="phoneapprover" type="text" id="it16" size="30" maxlength="30" />
<br />
<small>999-999-9999</small><br />
</fieldset>
</div>
I would like to give users the option to add all of this info to this form more than 1x before submitting. (say 10x max) I have run a couple ideas through my head. 1 is using Javascript to create the new fields and then parse them with my php script somehow. 2 is put say 10 code snips just like the form above in the code and hide them until the user clicks ADD ANOTHER.
Each input needs to be unique as I am submitting this info thought a simple $_REQUEST php script. I understand how to do this with 1 input and a for each loop, but am not sure how to make it work with such a large amount of inputs, labels, etc...
<?php
foreach($_POST['newdata'] as $value) {
echo "$value <br />";
}
?>
Anyone have some suggestions on the best way to go about this? I am not sure adding his form via JS is the best idea, so just displaying the new info from a hidden div seems quicker and easier...
If you append [] to your form field names, PHP will take those fields and turn them into an array, e.g.
<input type="text" name="field[]" value="first" />
<input type="text" name="field[]" value="second" />
<input type="text" name="field[]" value="third" />
would produce the following $_POST structure:
$_POST = array(
'field' => array(
0 => 'first',
1 => 'second',
2 => 'third',
)
);
The alternative is to append incrementing numbers to each field name, as you duplicate the existing field sets for each new block. This provides a nice separation between blocks and allows you guarantee that related fields have the same numerical tag, but it does complicate processing.
It's not so difficult: main idea is to use IDs for each iteration, so your inputs will have unique names and will be processed without problems
for ($i=0;$i<10;$i++){
echo "<input name='removeaccess' type='text' id='it14_{$i}' size='12' maxlength='12' />";
}
So, you take your code of current set of inputs with lables and add to input names IDs, formed on each circle iteration. Be carefull about ' and "!
Each div with the class "row" is added upon request from the user, to be able to add multiple items at once. So now is the question how I'll collect all the forms in to an array that PHP can read (like JSON for instance). I'll guess that there's already some easy and effective way of doing this?
<div class="container">
<div class="row">
<input type="text" name="value1" id="textfield" />
<input type="text" name="value2" id="textfield" />
<input type="text" name="value3" id="textfield" />
</div>
</div>
Here's what I would like to achieve out of the shown example:
array(
array ('value1' => '',
'value2' => '',
'value3' => '')
);
Thanks!
Update:
The form will be handled with PHP and it would be super to be able to do something like a foreach loop on the specific container-div content.
Give each 'group' of inputs the same name, then add square brackets to the end
<div class="container">
<div class="row">
<input type="text" name="value1[]" id="textfield" />
<input type="text" name="value2[]" id="textfield" />
<input type="text" name="value3[]" id="textfield" />
</div>
<div class="row">
<input type="text" name="value1[]" id="textfield" />
<input type="text" name="value2[]" id="textfield" />
<input type="text" name="value3[]" id="textfield" />
</div>
</div>
When you post the form, your php $_POST variable will then contain arrays for value1, value2 and value2:
var_dump($_POST); // array('value1' = array(...
You can then iterate through to 'regroup' the rows within PHP (but first, i'd change the field names to field1 etc rather than value1):
$rows = array(); // set up an empty array to hold your rows
// loop through each POST var
foreach($_POST AS $key=>$field) {
if(is_array($field)) {
foreach($field AS $rowIndex=>$fieldValue) {
$rows[$rowIndex][$field] = $fieldValue; // put the value in a the array by row, field
}
}
}
var_dump($rows);
This would give:
array(
[0] => array(
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3'
),
[1] => array(
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3'
),
...
)
<div class="container">
<div class="row">
<input type="text" name="value[0][value1]" class="textfield" />
<input type="text" name="value[0][value2]" class="textfield" />
<input type="text" name="value[0][value3]" class="textfield" />
</div>
<div class="row">
<input type="text" name="value[1][value1]" class="textfield" />
<input type="text" name="value[1][value2]" class="textfield" />
<input type="text" name="value[1][value3]" class="textfield" />
</div>
</div>
Changed id to class as reusing the same id is invalid HTML.
To convert XML to JSON you can try with:
Services_Json from PEAR: http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp
the Zend_Json component of the Zend Framework: http://framework.zend.com/manual/en/zend.json.xml2json.html