How can I insert appended input field data to mySQL database? - php

I append some input fields to my container and want to add for each an entry in my mysql database. This is working well so far:
<?php
if (isset($_POST['submit_val'])) {
if ($_POST['name']) {
foreach ( $_POST['name'] as $key=>$value ) {
$pdo = $db->prepare('INSERT INTO friends (name) values(:name) ');
$pdo->execute(array(
':name' => $value,
));
}
}
echo "<i><h2><strong>" . count($_POST['name']) . "</strong> items added</h2></i>";
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<form method="post" action="">
<div id="container">
<p id="add_field"><span>Click To Add</span></p>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<script type="text/javascript">
var counter = 0;
$(function() {
$('p#add_field').click(function() {
counter += 1;
$('#container').append(
'<strong>No. ' + counter + '</strong><br />' + '<input id="field_' + counter + '" name="name[]' + '" type="text" /><br/>');
});
});
</script>
But I wish to have as fields not only name, also age and gender:
$('#container').append('<strong>No. ' + counter + '</strong><br />' + '<input id="field_' + counter + '" name="name[]' + '" type="text" /><input id="field_' + counter + '" name="age[]' + '" type="text" /><input id="field_' + counter + '" name="gender[]' + '" type="text" /><br/>');
and add them into the database:
$pdo = $db->prepare('INSERT INTO friends (name,age,gender) values(:name,:age,:gender) ');
$pdo->execute(array(
':name' => $value,
':age' => $value,
':gender' => $value,
));
But now I have a logical problem of understanding. How can I get the other values into my foreach loop foreach ( $_POST['name'] as $key=>$value ) { because I need one loop for all values together?
I could imagine something like this:
foreach ( $_POST['name'] as $key=>$name && $_POST['age'] as $key=>$age && $_POST['gender'] as $key=>$gender ) {

Assuming occurrences of all the three fields are same you can use:
foreach($_POST['name'] as $key=>$val){
echo $val." ".$_POST['age'][$key]." ".$_POST['gender'][$key]."<br>";// you can use these value in your insert
}

Related

HTML form inputs to PHP Array. Not all values are posted

So I have this form:
<form data-ajax="false" name="frm" action="cmd_go.php" method="post" >
<input type="hidden" name="cmd" value="insertarlineapedidomultiple">
<input type="hidden" name="mod" value="yes">
<!--<input id="insertList" type="hidden" name="insertList" value="">-->
<input type="hidden" name="o" value="<?php echo $o ?>">
<div id="div_lista_familias" data-role="collapsibleset" data-content-theme="a" data-iconpos="right">
</div>
<input class="insertar btn-azul ui-btn ui-corner-all" data-role="none" type="submit" value="Insertar"/>
</form>
Then we have some Javascript code to populate the form content after calling a web service:
function listaProductos(alb, fam){
var ok = false;
$.ajax({
type: 'GET',
url: url_servicio + alb + '/' + fam + '/productos',
dataType: "json", // data type of response
//async: false,
error: function(){
ok = false;
},
success: function(data){
var content;
var acum = 0;
for(i=0; i<data.length; i++){
ok = true;
var qty = get_item_qty_inline(data[i].itemid);
var qty2 = get_item_qty2_inline(data[i].itemid);
var qty3 = get_item_qty3_inline(data[i].itemid);
var dto = get_item_dto1_inline(data[i].itemid);
content = '<fieldset class="ui-grid-d">';
content += '<div class="ui-block-a"><label for="name">';
content += data[i].itemid + ' ' + data[i].nombre + '</div>';
content += '<div class="ui-block-c ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty + '" placeholder="Uds1" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<div class="ui-block-b ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number" name="dtoporc1[]" pattern="[0-9]*" id="number-pattern"'
content += ' value="' + dto + '" placeholder="%Dto1"></div>';
content += '<div class="ui-block-d ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad2[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty2 + '" placeholder="Uds2" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<div class="ui-block-e ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad3[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty3 + '" placeholder="Uds3" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<input type="hidden" name="idalbaran[]" value="' + alb +'">';
content += '<input type="hidden" name="itemid[]" value="' + data[i].itemid +'">';
content += '<input type="hidden" name="famalbaran[]" value="' + fam +'">';
content += '<input type="hidden" name="itemdesc[]" value="' + data[i].nombre +'">';
content += '<input type="hidden" name="precioventa[]" value="' + data[i].precio + '">';
content += '<input type="hidden" name="dtoporc2[]" value>';
content += '<input type="hidden" name="dtoporc3[]" value>';
$('#'+fam.replace(/ /g, '_')+'_content').append(content);
acum += parseFloat(qty || 0) + parseFloat(qty2 || 0) + parseFloat(qty3 || 0);
$('#'+fam.replace(/ /g, '_')+' .ui-li-count').html(acum);
}
},
complete: function(data, status){
if (!ok){
$('#'+fam.replace(/ /g, '_')).remove();
}
}
});
}
Finally, this is the PHP code we have in cmd_go.php
//GET variables
if(isset($_GET)){
$params = array_keys($_GET);
for ($i=0;$i<count($params);$i++)
if(isset($_GET[$params[$i]])){
$nv=$params[$i];
$$nv=$_GET[$params[$i]];
}
}
//POST variables
if(isset($_POST)){
$params = array_keys($_POST);
for($i=0;$i<count($params);$i++)
if(isset($_POST[$params[$i]])){
$nv=$params[$i];
$$nv=$_POST[$params[$i]];
//print "$nv : ".$$nv.'<br />';
}
}
var_dump($itemid);
The problem is that not all values are posted, because our $itemid array only has 91 elements, when our web service returns about 400. Out HTML form is correctly displayed with all 400 items, but out PHP var_dump returns:
array(91){[0]=>string(6) "173771" [1]=>string(6) "173772" [2]=>string(6) "564814"...[90]=>string(6) "548115"}
Any ideas on why POST could be taking only 91 records??
You need to check max_input_vars value in php.ini. It can lead to such behavior.
http://php.net/manual/en/info.configuration.php#ini.max-input-vars

Save values of multiple text boxes using jquery and mysql

How to insert dynamically generated field values to backend using mysql.
Im trying to add rows with text box and drop down using jquery and auto saving
the field values at regular intervals.
So i need to fetch the ids of the textboxes and drop down, but currently i get the id of only the first text box and drop down.
$(function() {
$("#btnAdd").bind("click", function() {
AddControl();
});
$("#btnGet").bind("click", function() {
var values = "";
$("input[name=DynamicTextBox]").each(function() {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
var i = 1;
var Ids = [];
$('[id*=ddl]').each(function() {
$(this).attr("id", "ddl" + i);
Ids.push(i);
i++;
});
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var resultIds = Ids.join(',');
$('[id*=hfDropDownIds]').val(resultIds);
});
});
function AddControl() {
var Id = parseInt($('[id*=hfDDLId]').val()) + 1;
var ddlId = "ddl" + (Id);
var div = $("<div />");
div.html(getDropDownList(ddlId, ddlId));
div.append(GetDynamicTextBox(''));
$("#TextBoxContainer").append(div);
$('[id*=hfDDLId]').val(Id);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
if (previousDropDownId != '') {
$('[id*=hfDropDownIds]').val(previousDropDownId + ',' + Id);
} else {
$('[id*=hfDropDownIds]').val(Id);
}
return false;
}
function getDropDownList(name, id) {
var combo = $("<select></select>").attr("id", id).attr("name", name).attr("runat", "server").attr("class", "class").attr("required", "required");
combo.append("<option value=" + "" + ">" + "Select Category" + "</option>");
combo.append("<option value=" + "1" + ">" + "1" + "</option>");
combo.append("<option value=" + "2" + ">" + "2" + "</option>");
combo.append("<option value=" + "3" + ">" + "3" + "</option>");
return combo;
}
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" id="ingr_name" type="text" value = "' + value + '" required/>&nbsp' + '<input name = "DynamicTextBox" type="text" value="' + value + '" required/>&nbsp' + '<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<input id="btnAdd" type="button" value="Add" />
<br/>
<br/>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br/>
<input type="hidden" id="hfSelectedValue" runat="server" />
<input type="hidden" id="hfDropDownIds" value="" runat="server" />
<input id="btnGet" type="button" value="Get Values" />
<input type="hidden" id="hfDDLId" value="0" />
</div>
</form>
Code for inserting in the backend
Assunimg i have given the id for the text box as 'ingr_name' im posting the same as :
<?php
$con=mysqli_connect("localhost","root","pass","DB");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['txt_area']) && $_POST['txt_area'] != '') {
$ingr_name = mysqli_real_escape_string($con,$_POST['ingr_name']);
$qry = "Select count(*) as cnt from table";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_array($res);
if ($row['cnt'] == 0) {
$qry_ins = 'my insert query';
}
?>
#SachinSachin if you want to insert only one text box value try the below code
function insert_data(){
var url = "insert.php";
$.ajax({
url : url,
type: "POST",
data: $('#formid').serialize(),
success: function(data)
{
alert(data);
}
});
}
call this function on submit button and in insert.php you get the values using post method as usual and insert them in mysql. if it is success print echo "inserted"; else print echo "failed"; you will get this status in alert message in above insert_data() function. Here i assumed you are using php as backend if not use your language with same process.

Dynamically Add Input Fields And Submit To Database With jQuery and PHP

I want to Post Multiple values for foreach function because i have multiple dynamic textbox then how should i send the values in database??
how to write foreach function for dat..
the code below display 2 multiple textbox but didnt submit values in databse
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
+'<strong>HolidayReason ' + counter + '</strong> '
+ '<input id="holidayreason_' + counter + '" name="holireason[]' + '" type="text" />'
);
});
});
</script>
<body>
<?php
if (isset($_POST['submit_val'])) {
if (($_POST['dynfields'])&& ($_POST['holireason'])) {
//$aaa=array($_POST['dynfields']);
foreach ($_POST['dynfields'] as $key=>$value)
{
$values = mysql_real_escape_string($value);
//$holireasons = mysql_real_escape_string($holireason);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')" );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";
mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="add_field"><span>Click To Add Hobbies</span></p>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
</body>
</html>
try this
<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
+'<strong>HolidayReason ' + counter + '</strong> '
+ '<input id="holidayreason_' + counter + '" name="holireason[]' + '" type="text" />'
);
});
});
</script>
<body>
<?php
if (isset($_POST['submit_val'])) {
if (($_POST['dynfields'])&& ($_POST['holireason'])) {
$no = count($_POST['dynfields']);
for ($i=0; $i <$no ; $i++) {
echo $_POST['dynfields'][$i]."<br>";
echo $_POST['holireason'][$i]."<br>";
$abc = mysql_real_escape_string($_POST['dynfields'][$i]);
$xyz = mysql_real_escape_string($_POST['holireason'][$i]);
$sql = "INSERT INTO my_hobbies (hobbies,Holidayreason) VALUES ('$abc','$xyz')";
mysql_query($sql);
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";
mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<div id="container">
<p id="add_field"><span>Click To Add Hobbies</span></p>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
</body>
</html>
Use array_combine as follows.
foreach(array_combine($_POST['dynfields'] , $_POST['holireason']) as $dyn => $holi) {
$abc = mysql_real_escape_string($dyn);
$xyz = mysql_real_escape_string($holi);
$sql = mysql_query ("INSERT INTO my_hobbies (hobbies,Holidayreason) VALUES ('".$abc."','".$xyz."')");
}
100% works fine.

jquery php count loop on name to email

In form, I will be adding product info in. looping name eg. pname1, pname2 when add.
I realise now that when i wanna send to email we need the 'name'. what code should i put on php file to loop the pname?
noted: my form and php code is not in the same file.
or i should put them together and click to loop?
Php file put this?
<?php
$x=1;
while($x<=10)
{
echo "The number is: $x <br>";
echo ;
$x++;
}
?>
form in html
<div class="" id="" name="productlist"> <!-- Add Product Here -->
<ol><input class="fpname" type="text" id="addpname"placeholder="Product Name"/><input class="fpqty" type="number" id="addpqty" placeholder="Quantity"/><input class="fpprice" type="text" id="addpprice" placeholder="Price per Item"/><input type="button" id="padd" value="add"/>
</br><font color="red" size="1.5"><i>*Becareful when adding the Product, once added you are unable to edit the information except changing the quantity.</i></font>
</ol>
<ol id="addhereform"><input type="text" class="fpname" value="Product Name" readonly/><input class="fpqty" type="text" id="pqty" value="Quantity" readonly/><input type="text" class="fpprice" value="Total Price" readonly/>
</ol>
<ol><input class="fpname" id="fpships" type="text" Value="" readonly/><input class="fpqty" id="overallqty" type="text" value="" readonly/><input class="fpprice" type="text" id="overallprice" value="" readonly/>
</ol> <!-- Result -->
</div> <!-- Add Product End Here -->
jquery add button
var count = 1;
$('#padd').click(function(){
var pname = $('#addpname').val();
var pqty = $('#addpqty').val();
var pprice = $('#addpprice').val();
var totalpprice = (pqty * pprice).toFixed(2);
$('#addhereform').append('<li><input class="fpname" type="text" id="pname" name="pname' + count + '" value="' + pname + '" readonly/><input class="fpqty" type="number" id="pqty" name="pqty' + count + '" value="' + pqty + '"/><input type="text" id="pprice" name="pprice' + count + '" value="' + pprice + '" readonly hidden/><input class="fpprice" type="text" id="totalpprice" name="totalpprice' + count + '" value="' + totalpprice + '" readonly/><input type="button" id="premove" value="X"/></li>').before('</li>');
count++;
});
Ans:
$name1 = $_POST["name1"];
$name2 = $_POST["name2"];
$name3 = $_POST["name3"];
# and so on...
for($i = 1; $i <=5; $i++){
$productlist = ${'name' . $i};
echo $productlist;}
Thanks for everyones help,
Here's another method(better) I just found. no need to type all the super long loop way.
Stristr is find name keyword.
if($_POST){
foreach($_POST as $key => $value){
if(stristr($k, 'pname')){
echo "$v";
}
if(stristr($k, 'pqty')){
echo "$v";
}
if(stristr($k, 'pprice')){
echo "$v";
}
if(stristr($k, 'ptotalprice')){
echo "$v</br>";
}
}
}

auto populate data with dropdown

ALL EDITED
Hi,
How can I auto populate the data from db by dropdown selected? and my dropdown result already appear as well, the code as following:
<?php
echo '<tr>
<td>'.$customer_data.'</td>
<td><select name="customer_id" id="customer_id" onchange="getCustomer();">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
has html view code as
<select name="customer_id" id="customer_id" onchange="getCustomer();">
<option value="8">admin</option>
<option value="6">customer1</option>
<option value="7" selected="selected">FREE</option>
</select>
now if one of dropdown selected i want another e.g. <?php echo $firstname; ?>, <?php echo
$lastname; ?>
appear in
<tr>
<td><div id="show"></div></td>
</tr>
that based on customer id/name selected
to do that i try to use json call as following:
<script type="text/javascript"><!--
function getCustomer() {
$('#show input').remove();
$.ajax({
url: 'index.php?p=customer/customers&customer_id=' + $('#customer_id').attr('value'),
dataType: 'json',
success: function(data) {
for (i = 0; i < data.length; i++) {
$('#show').append('<input type="text" name="customer_id" value="' + data[i]['customer_id'] + '" /><input type="text" name="firstname" value="' + data[i]['firstname'] + '" />');
}
}
});
}
getCustomer();
//--></script>
the php call json placed at customer.php with url index.php?p=page/customer)
public function customers() {
$this->load->model('account/customer');
if (isset($this->request->get['customer_id'])) {
$customer_id = $this->request->get['customer_id'];
} else {
$customer_id = 0;
}
$customer_data = array();
$results = $this->account_customer->getCustomer($customer_id);
foreach ($results as $result) {
$customer_data[] = array(
'customer_id' => $result['customer_id'],
'name' => $result['name'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname']
);
}
$this->load->library('json');
$this->response->setOutput(Json::encode($customer_data));
}
and the db
public function getCustomer($customer_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");
return $query->row;
}
but i get the wrong return as following
is there someone please how to solved it to more better? thanks in advance
Something on your PHP-Coding style:
For a PHP Code-Block, don't use new php-Tags for every line. Also, if you want an HTML-Output from PHP, you can use the echo-Method to do this. So your Code looks like this:
<?php
echo '<tr>
<td>'.$customer.'</td>
<td><select name="customer_id">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
The thin is, every time the PHP-Interpreter finds an opening PHP-Tag, it starts Interpreting it's code, and when it finds a closing Tag, it stops doing this. So in your code, the interpreter starts and stops all the time. This is not very performance.
I guess you want to set the value of your text-fields? That's really not what PHP does. That is more a JavaScript thing, because it actually happens in the Browser, not on the Server.
Instead of this:
success: function(data) {
for (i = 0; i < data.length; i++) {
$('#show').append('<input type="text" name="customer_id" value="' + data[i]['customer_id'] + '" /><input type="text" name="firstname" value="' + data[i]['firstname'] + '" />');
}
}
in Your JS AJAX call do this:
success: function(data) {
$('#show').append('<input type="text" name="customer_id" value="' + data['customer_id'] + '" /><input type="text" name="firstname" value="' + data['firstname'] + '" />');
}
as Your PHP function returns ONLY ONE object. If You then loop over the objects property You loop over one character of the property value indeed...

Categories