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.
Related
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
}
The given below is my php code, I want to extract values from database that matches the text inserted by user in text field when clicked on submit button using AJAX.
The given below is the code:
<!doctype html>
<html>
<head>
<title>Bootstrap Table</title>
<link rel="stylesheet" href="bootstrap/bootstrap-4.0.0-alpha.6-dist/css/bootstrap.min.css">
<script src="bootstrap/jquery-3.1.1.min.js"></script>
<script src="bootstrap/bootstrap-4.0.0-alpha.6-dist/js/bootstrap.min.js"></script>
<style>
.container{margin:auto;}
</style>
</head>
<body>
<div class="container">
</div>
<div class='col-sm-3' style='margin-left:10%;'>
<form class='navbar-form' action='' method='POST'>
<div class='input-group'>
<input type='text' class='form-control' placeholder='Search' name='srch-term' id='search_data'>
<div class='input-group-btn'>
<input class='btn btn-search' type='submit' id='search_button' style='cursor:pointer;'>Search</button>
</div>
</div>
</form>
</div>
<div class="result">
</div>
<script id="source" language="javascript" type="text/javascript">
$('#search_button').click(function() {
var search_data = 'input[name=srch-term]'.val();
$.ajax({
type: "POST",
url: 'bootstrap_table_db2.php',
data: {search: search_data},
success: function(result) {
for (var i in result) {
var row = result[i];
var employee_name = row[1];
var email = row[2];
var message = row[3];
var date = row[4];
result+= "<tr>" +
"<td width='25%'>" + employee_name + "</td>" +
"<td width='25%'>" + email + "</td>" +
"<td width='25%'>" + message + "</td>" +
"<td width='25%'>" + date + "</td>" +
"</tr>";
}
$(".result").html(result);
}
});
});
</script>
</body>
</html>
The given below is bootstrap_table_db2.php.
<?php
mysql_connect("localhost", "root", "password") || die(mysql_error());
mysql_select_db("emp") || die(mysql_error());
if(isset($_POST['search']) && !empty($_POST['search'])) {
$result2 = mysql_query("SELECT * FROM employee WHERE Employee_name = 'search'");
$data2 = array();
while ( $row = mysql_fetch_row($result2) ) {
$data2[] = $row;
}
echo json_encode( $data2 );
}
?>
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/> ' + '<input name = "DynamicTextBox" type="text" value="' + value + '" required/> ' + '<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.
I am using the following script to fetch records from my database and put them into select boxes using jquery, ajax and php. The select boxes are also styled and added features using Select 2
http://ivaynberg.github.io/select2/select-2.1.html#basics
If I select a customer from the first select box and then select a vehicle from the second box this works fine........if I then change my mind and select a different company, the vehicle box stays on the last reg and doesn't revert back to :
<option>Select A Customers Vehicle</option>
If I then click on the vehicle select box I can select the vehicles from the company and the 'ghost vehicle' from the last query vanishes, so it does work, its just when I change the company again I would like it just to reset the vehicle box back to its default again until I select a vehicle.
This is the Main Page :
<script src="js/jquery/jquery.js"></script>
<script src="js/jqueryui/js/jquery-ui.js"></script>
<link href="js/select2/select2.css" rel="stylesheet"/>
<script src="js/select2/select2.js"></script>
<script>
$(document).ready(function() { $("select").select2(); });
</script>
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
if (isset($_SESSION['key'])) {$sessionkey = $_SESSION['key'];}else {$sessionkey = '';}
if ($sessionkey == 'sbhjbKA2bsbhjbKA209bhjbKA2bsbhjbKA209KaXff19u0bsbhjbKA209KaXff19u9Ka'){
include 'connectmysqli.php';
echo '<link rel="stylesheet" href="css/template/template.css" />';
echo '<strong class="pagetitle">Add New Sale</strong>
';
$saleID = rand().rand();
$today = date("Y-m-d");
echo '<form method="post" action="addsalesubmit.php">';
echo '<input type="hidden" value="'.$saleID.'" name="saleID" id="saleID">';
echo '<input type="hidden" value="'.$today.'" name="date" id="date">';
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Select test</title>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#customer').on('change', function (){
$.getJSON('select.php', {customerId: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + ' - ' + data[x]['make'] + ' - ' + data[x]['model'] + '</option>';
}
$('#vehicle').html(options);
});
});
});
</script>
</head>
<body>
<br>
<select id="customer">
<option>Please Select / Search For A Customer</option>
<?php
$sql = <<<SQL
SELECT *
FROM `customers`
SQL;
if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
while($row = $result->fetch_assoc()){
if ($row['bussinessname'] == ''){$name = $row['title'].' '.$name = $row['firstname'].' '.$name = $row['surname'];}else
{$name = $row['bussinessname'];}
echo '<option value="'.$row['customerID'].'">'.$name.'</option>';
}
echo '</select></p>';
?>
</select>
<br>
<br>
<select id="vehicle">
<option>Select A Customers Vehicle</option>
</select>
</body>
</html>
<?php
}
else
{echo '<h1 style="font-family:Verdana, Geneva, sans-serif; color:red;">Access Denied !</h1>';}
?>
This is the php script that does all the fetching :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['customerId'];
$sql = 'SELECT * FROM vehicles WHERE customerID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'id' => $row['vehicleID'],
'reg' => $row['reg'],
'make' => $row['make'],
'model' => $row['model']
);
}
echo json_encode($json);
?>
On every call of the onchange first empty the second dropdown
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#customer').on('change', function (){
$('#vehicle').html("<option value=''>Select</option>");// add this on each call then add the options when data receives from the request
$.getJSON('select.php', {customerId: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + ' - ' + data[x]['make'] + ' - ' + data[x]['model'] + '</option>';
}
$('#vehicle').html(options);
$("select").select2();
});
});
});
</script>
the following is not asked but i have to advice you that there are some additional errors in your code:
echo '</select></p>';
?>
</select>
there are two </select> and one </p> without a starting <p> at the end of your customer select box
I'm trying to populate a third set of radiobuttons as an addition to the following script: http://www.electrictoolbox.com/json-data-jquery-php-radio-buttons/
For some reason I cannot seem to fill the third set with the corresponding data. It just stays blank :(
Calling the populateFruittype() function only gives back [ ], while populateFruitVariety() returns the json data correctly.
getdata.php (DB connection / fetching data)
<?php
$dsn = "mysql:host=localhost;dbname=mydb";
$username = "username";
$password = "password";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['fruitName'])) {
$stmt = $pdo->prepare("SELECT DISTINCT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['fruitName']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_GET['fruitVariety'] )) {
$stmt = $pdo->prepare("SELECT DISTINCT fruittype FROM fruit WHERE variety = ? ORDER BY fruittype");
$stmt->execute(array($_GET['fruitVariety']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Toevoegen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function populateFruitVariety() {
var fruitName = $('input[name=fruitName]:checked').val();
$.getJSON('getdata.php', {fruitName: fruitName}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitVariety" value="' + array['variety'] + '" />' + array['variety'] + '</label> ';
});
$('#varieties').html(html);
});
}
function populateFruittype() {
var fruitVariety = $('input[name=fruitVariety]:checked').val();
$.getJSON('getdata.php', {fruitVariety: fruitVariety}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
}
$(function() {
$('input[name=fruitName]').change(function() {
populateFruitVariety();
});
});
$(function() {
$('input[name=fruitVariety]').change(function() {
populateFruittype();
});
});
</script>
</head>
<body>
<form>
<div>
<strong>Fruit:</strong>
<label><input type="radio" name="fruitName" value="Apple"/>Apple</label>
<label><input type="radio" name="fruitName" value="Banana"/>Banana</label>
<label><input type="radio" name="fruitName" value="Orange"/>Orange</label>
<label><input type="radio" name="fruitName" value="Pear"/>Pear</label>
</div>
<div>
<strong>Variety:</strong>
<span id="varieties"></span>
</div>
<div>
<strong>Type:</strong>
<span id="fruittype"></span>
</div>
</form>
</body>
</html>
The DB query and content can be found here: http://www.electrictoolbox.com/mysql-example-table/
Just add:
`fruittype` varchar(50) NOT NULL
and fill it with some custom values.
1) DB uddate
ALTER TABLE fruit ADD COLUMN `fruittype` varchar(50) NOT NULL;
UPDATE fruit SET fruittype = 'description' /* WHERE name = 'Apple'*/;
2) code update
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Toevoegen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('input[name=fruitName]').change(function() {
var fruitName = $('input[name=fruitName]:checked').val();
$.getJSON('test.php', {fruitName: fruitName}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<input type="radio" name="fruitVariety" value="' + array['variety'] + '" /><label>' + array['variety'] + '</label> ';
});
$('#varieties').html(html);
});
});
$('input[name=fruitVariety]').live('click', function() {
var fruitVariety = $('input[name=fruitVariety]:checked').val();
$.getJSON('test.php', {fruitVariety: fruitVariety}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<input type="radio" name="fruitType" value="' + array['fruittype'] + '" /><label>' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
});
});
</script>
</head>
<body>
<form>
<div>
<strong>Fruit:</strong>
<label><input type="radio" name="fruitName" value="Apple"/>Apple</label>
<label><input type="radio" name="fruitName" value="Banana"/>Banana</label>
<label><input type="radio" name="fruitName" value="Orange"/>Orange</label>
<label><input type="radio" name="fruitName" value="Pear"/>Pear</label>
</div>
<div>
<strong>Variety:</strong>
<span id="varieties"></span>
</div>
<div>
<strong>Type:</strong>
<span id="fruittype"></span>
</div>
</form>
</body>
</html>