Have two variables in one foreach bad insert - javascript

Hello i have a trouble with my code.
I have HTML with JS:
$(document).ready(function () {
// allowed maximum input fields
var max_input = 5;
// initialize the counter for textbox
var x = 1;
// handle click event on Add More button
$('.add-btn').click(function (e) {
e.preventDefault();
if (x < max_input) { // validate the condition
x++; // increment the counter
$('.wrapper').append(`
<div class="input-box">
<input type="text" name="input_name[]"/>
<input type="text" name="input_price[]">
Remove
</div>
`); // add input field
}
});
// handle click event of the remove link
$('.wrapper').on("click", ".remove-lnk", function (e) {
e.preventDefault();
$(this).parent('div').remove(); // remove input field
x--; // decrement the counter
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-box">
<input type="text" name="input_name[]">
<input type="text" name="input_price[]">
<button class="btn add-btn">+</button>
</div>
</div>
and i need insert in DB all inputs (name and price)
Now if i trying insert only first line.
php script:
This is a function and $id_produkt is GET from url.
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){
$input_name = $_POST["input_name"];
$input_price = $_POST["input_price"];
foreach (array_combine($input_name, $input_price) as $field_name => $field_price){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $field_name, $field_price);
$result = db_query($sql, $data);
return $result;
}
}
Can help me please ? I am tired

I make function like that and working.
function insertVariantsProduct($id_produkt){
$userData = count($_POST["input_name"]);
if ($userData > 0) {
for ($i=0; $i < $userData; $i++) {
if (trim($_POST['input_name'] != '') && trim($_POST['input_price'] != '')) {
$var_id = $_POST["input_id"][$i];
$name = $_POST["input_name"][$i];
$price = $_POST["input_price"][$i];
if(empty($var_id) && !isset($var_id)){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $name, $price);
}else {
$sql = "UPDATE variant_product SET name='$name',price='$price' WHERE id='$var_id' ";
$data = null;
}
$result = db_query($sql, $data);
}
}
return $result; // This should be out of loop because it's will break the loop
}
}

Related

Woocommerce | Plus Minus remove negative numbers (min_value)

I ask you for help please, I haven't come out of it for hours.
I set the quantity selector on the Woocommerce shop page,
which automatically puts the item in the cart and / or removes it.
I have a big problem, when I am on zero and I press - the numbers go negative, I would make sure that it cannot go below zero.
Thanks so much!!
Function.php
// Remove Add To cart Button
remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
// Add our Quanity Input
add_action('woocommerce_after_shop_loop_item', 'QTY');
function QTY()
{
global $product;
?>
<div class="shopAddToCart">
<button value="-" class="minus2" >-</button>
<input type="text"
disabled="disabled"
size="2"
value="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
id="count"
data-product-id= "<?php echo $product->get_id() ?>"
data-in-cart="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['in_cart'] : 0;
?>"
data-in-cart-qty="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
class="quantity qty qty-botton"
max_value = "<?php echo ($product->get_max_purchase_quantity() == -1) ? 1000 : $product->get_max_purchase_quantity(); ?>"
min_value = <?php echo $product->get_min_purchase_quantity(); ?>
>
<button type="button" value="+" class="plus2" >+</button>
</div>
<?php
}
//Check if Product in Cart Already
function Check_if_product_in_cart($product_ids)
{
foreach (WC()->cart->get_cart() as $cart_item):
$items_id = $cart_item['product_id'];
$QTY = $cart_item['quantity'];
// for a unique product ID (integer or string value)
if ($product_ids == $items_id):
return ['in_cart' => true, 'QTY' => $QTY];
endif;
endforeach;
}
//Add Event Handler To update QTY
add_action('wc_ajax_update_qty', 'update_qty');
function update_qty()
{
ob_start();
$product_id = absint($_POST['product_id']);
$product = wc_get_product($product_id);
$quantity = $_POST['quantity'];
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item):
if ($cart_item['product_id'] == $product_id) {
WC()->cart->set_quantity($cart_item_key, $quantity, true);
}
endforeach;
wp_send_json('done');
}
*.js jQuery on Footer
jQuery(document).ready(function ($) {
"use strict";
// Add Event Listner on the Plush button
$('.plus2').click(function () {
if (parseInt($(this).prev().val()) < parseInt($(this).prev().attr('max_value'))) {
$(this).prev().val(+$(this).prev().val() + 1);
var currentqty = parseInt($(this).prev().attr('data-in-cart-qty')) + 1;
var id = $(this).prev().attr('data-product-id');
var data = {
product_id: id,
quantity: 1
};
$(this).prev().attr('data-in-cart-qty', currentqty);
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
}
});
$('.minus2').click(function () {
$(this).next().val(+$(this).next().val() - 1);
var currentqty = parseInt($(this).next().val());
var id = $(this).next().attr('data-product-id');
var data = {
product_id: id,
quantity: currentqty
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'update_qty'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
});
});
Just add a check before running the line:
$(this).next().val(+$(this).next().val() - 1);
that will become:
if ( $(this).next().val() > 0 ) {
$(this).next().val(+$(this).next().val() - 1);
}
Also note that you are using an identical id for each quantity input of each product. The id attribute value should be unique on the page.
Here you can find some methods of adding plus and minus buttons in the quantity field of the add to cart form (which you could take inspiration from):
Custom plus and minus quantity buttons in Woocommerce 3
WooCommerce plus and minus buttons
WooCommerce: Add to Cart Plus & Minus Buttons
Thanks Vincenzo Di Gaetano.
I solved it like this:
$('.minus2').click(function () {
var $minus2 = $(this);
var oldValue = $minus2.parent().find("input").val();
if (oldValue > 0) {
$(this).next().val(+$(this).next().val() - 1);
.....

Edit input name when chceckbox clicked

I try to edit name field for the specific input. I need this to get all the variables from this site and add them to my invoice script. I have two divs with client select and service select
HTML:
<div class="service-select">
<?php
$query = "SELECT id,service_name,quantity,net_price,gross_value FROM service";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
?>
<div class='single-service-<?php echo $row["id"]; ?>'>
<input type='checkbox' name=''>
<input type="text" name="service_name" class='name' value="<?php echo $row["service_name"]; ?>" placeholder='NAZWA USŁUGI' disabled/>
<label>Ilość:</label><input type="number" name="quantity" value="<?php echo $row["quantity"]; ?>" placeholder='ILOŚĆ' disabled/>
<label>Cena netto:</label><input type="number" name="net_price" value="<?php echo $row["net_price"]; ?>" placeholder='CENA NETTO' disabled/>
</div>
<?php
}
$result->free();
}
?>
</div>
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for(var i=0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var div = this.parentNode;
var name_input = div.getElementsByClassName("name");
var name = name_input.name;
var parent_div = div.parentNode;
var x = div.childNodes;
console.log(name_input);
if (parent_div.className == 'service-select') {
if (name_input.name != 'service_chcecked[]') {
name_input.name = 'service_chcecked[]';
}
else {
name_input.name = 'service_name';
}
}
else {
if (name != 'client_chcecked[]') {
name_input.name = ['client_chcecked[]'];
}
else {
name_input.name = ['client_name'];
}
}
for(y=0; y < x.length; y++) {
if(x[y].type === "number" || x[y].type === "text") {
x[y].disabled = !x[y].disabled;
}
}
}, false);
};
My problem is that currently the given name is added to the div :/

how to auto increment a number everytime when a button is clicked on other page using javascript

I have a form created using HTML and CSS, this form is not for submitting any data in fact it's only for printing purposes.
This form has an input field at top left corner to put a unique 6 digit number to uniquely identify each form.
On the homepage, there is a button link to that form page and I want to increment that serial no which is by default 000000 every time a link button to this form page is clicked.
index.html:
form-1.html:
<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
You have two solution:
Using cookie
Using browser-session
Note: Please comment another solution, while using one solution
main-page.html
<html>
<head>
<title>Main Page</title>
</head>
<body>
Print
</body>
</html>
form-1.html
<html>
<head>
<title>Form Printing</title>
</head>
<body onload="loadNextSeqToForm()">
<form>
<input id="serial" class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
</form>
</body>
<script>
/*
//Solution 1: Using Cookies
function getNextSeq() {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);//Trim the empty space if exists
}
if (c.indexOf("next") == 0) {
var fragments = c.split("=");
if(fragments.length == 2 && !isNaN(fragments[1])) {
return parseInt(fragments[1]) + 1;
}
}
}
return "1";//default
}
function loadNextSeqToForm() {
var nextValue = getNextSeq();
document.cookie = "next=" + nextValue + ";";
document.getElementById("serial").value = formatToSixCharacters(nextValue);
}
function formatToSixCharacters(num) {
var numStr = num + "";
if(numStr.length < 6) {
var zeros = 6 - numStr.length;
for(var i = 1; i <= zeros; i++) {
numStr = "0" + numStr;
}
}
return numStr;
}
*/
//Solution 2: Using Session
function loadNextSeqToForm() {
var nextValue = sessionStorage.getItem("next") != null? sessionStorage.getItem("next") : 1;
document.getElementById("serial").value = formatToSixCharacters(nextValue);
sessionStorage.setItem("next", parseInt(nextValue) + 1)
}
function formatToSixCharacters(num) {
var numStr = num + "";
if(numStr.length < 6) {
var zeros = 6 - numStr.length;
for(var i = 1; i <= zeros; i++) {
numStr = "0" + numStr;
}
}
return numStr;
}
</script>
</html>
++ Code using PHP and MySQL
main-page.html
<html>
<head>
<title>Main Page</title>
</head>
<body>
<!-- Note this time we have to use PHP file reference -->
Print
</body>
</html>
form-1.php
<?php
session_start();
function getNextSequnceNumber() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "orders";
$nextSeq = 1;
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT next_seq FROM order_sequence";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($row = $result->fetch_assoc()) {
$nextSeq = $row["next_seq"];
}
}
//Update next sequence number in db
$sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
if (mysqli_query($conn, $sql)) {
//Updated successfully
//Write in log may be
}
$conn->close();
return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
DB Scripts
CREATE DATABASE orders;
USE orders;
CREATE TABLE order_sequence (
next_seq INT NOT NULL
);
-- DEFAULT VALUE
INSERT INTO order_sequence (next_seq)
VALUES(1);
Note: Make sure you replace your DB user name and password
SQLITE3 version of code as requested
form-sqlite.php
<?php
session_start();
class DBUtil extends SQLite3 {
function __construct() {
//Open db
$this->open("orders.db");
}
function createTableIfNotExists() {
//create table if not exists already
$sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
." next_seq INT NOT NULL"
.")";
$result = $this->exec($sql);
return $result;//Whether table created successfully or not
}
function updateNextSeqNumber($nextSeq) {
//update next sequnce number in db
$sql = "UPDATE order_sequence SET next_seq = ".$nextSeq;
$result = $this->exec($sql);
return $result;
}
function insertFirstTime() {
//insert first time
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
$result = $this->exec($sql);
return $result;
}
function getNextSeq() {
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$result = $this->query($sql);
$nextSeq = 1;
if($row = $result->fetchArray(SQLITE3_ASSOC)) {
$nextSeq = $row["next_seq"];
} else {
$this->insertFirstTime();//First sequence number, so that next update queries will be always successfull
}
$this->updateNextSeqNumber($nextSeq + 1);
return $nextSeq;
}
}
function getNextSequnceNumber() {
//Create new object of utility class
$db = new DBUtil();
if(!$db){
die("Connection failed: " . $db->lastErrorMsg());
}
//Check if connected
if($db->createTableIfNotExists()) {
$nextSeq = $db->getNextSeq();
return formatToSixCharacters($nextSeq);
} else {
die ("Error: " . $db->lastErrorMsg());
}
//close connection finally
$db->close();
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
++PHPDesktop With Sqlite Version
form-php-desktop-sqlite.php
Please include this PHPDesktop Helper file pdo.php provided by PHPDesktop. However this is small helper file, it does not serve big purpose, but it will help you for now.
Also read Using Sqlite with PHP Desktop
<?php
session_start();
include "./pdo.php";
function getNextSequnceNumber() {
//Open connection
$db_file = "./orders.sqlite3";
PDO_Connect("sqlite:$db_file");
//Create table if not exists
$sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
." next_seq INT NOT NULL"
.")";
PDO_Execute($sql);
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$nextSeq = PDO_FetchOne($sql);
if($nextSeq == null) {
$nextSeq = 1;
//Also insert first time record
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
PDO_Execute($sql);
}
//Update next time sequence
$sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
PDO_Execute($sql);
return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
A really simple way to do this is by using jQuery. Use the click event listener with the button link which will listen to every clicks made to that button, and increment the value with each clicks. With the starting value as 000000, store the incremented value into a variable and then use that variable on a desired page.
FOR EXAMPLE:
Consider that you have this button on the home.html page:
BUTTON
Now, using jQuery - listen to the click events from this link and store the incremented values on variable like this:
var count = 0,
default = '000000';
$('#linkcounter').click(function(e) {
e.preventDefault();
count++;
var ctxt = '' + count;
var incrementval = pad.substr(0, pad.length - ctxt.length) + ctxt;
});
// store the value into the local storage of DOM for the current session. this is done to retain the variable value even after a page is refreshed.
var incrementvallocal = incrementval;
localStorage.setItem("incrementvalueper", incrementvallocal);
The incremented value stored in the variable incrementval is sent to the localstorage. Now just use the value of this variable on desired page(in this example it is formpage.html).
If you want to set the placeholder text on the form page which has an input field like this:
<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
by the incremented value, then use this jQuery code:
// get incremented value from the local storage of DOM.
var getincval = localStorage.getItem("incrementvalueper");
$(document).ready(function(){
$('.serial-no').attr("placeholder", getincval);
});
This code uses the value of the variable getincval(which has the incremented click value) and sets it to the placeholder text of the input element which has the class .serial-no.
Let me know if this helps. :)

multiple textbox values storing in same column in php

I an using Javascript when click add button to show multiple text box. but i don't how to store these text box values in database table single column. here i attached my form input coding and javascript for add number of textbox. after submit my form it stores somthing like Array into my table.
<?php
if(isset($_POST['submit']))
{
Include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
$count = $_POST['count'];
for($i = 0 ; $i < $count ; $i++)
{
//$count++;
$routesmore = $_POST['routes_more'];
$routesmore2 = explode('.', $routesmore[0]);
}
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$routesmore2', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
my input box:
<div class="col-lg-8" id="img_upload">
<!-- <input type="text" id="file0" name="routes" style="background:none;width:185px;"> -->
<div id="divTxt"></div>
<p><a onClick="addproductimageFormField(); return false;" style="cursor:pointer;width:100px;" id="add_img_btn" class="btn btn-primary">Add Route</a></p>
<input type="hidden" id="aid" value="1">
<input type="hidden" id="count" name="count" value="0">
My Javascript:
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more"+count_id+"' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change In JS - Append routes_more[] in jQuery("#divTxt").append in place of routes_more'+count+'.
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more[]' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change in PHP Code - Find total count of routes_more textbox. And do accordingly. (No Need of checking how much count was there in your html code.)
<?php
if(isset($_POST['submit']))
{
include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
//For Routes More
$totalRoutesCount = sizeof($_POST['routes_more']);
$totalRoutes="";
for($i=0;$i<$totalRoutesCount;$i++)
{
$totalRoutes = $totalRoutes.$routesmore[$i].",";
}
$totalRoutes = rtrim($totalRoutes, ',');
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$totalRoutes', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
HTML :
<input type="text"
id="file0" name="routes[]"
style="background:none;width:185px;">
PHP:
INSERT Query:
'routes'(BD column) = serialize( $post['routes'] );
Display Time:
unserialize the column routes and print with foreach loop

how to solve theproblem with saving the data in an appended textbox

please help me out, i use isset to check if the index is defined but instead of saving the value of the textbox it stores 0.how shoul i do it? cause if i wont check if the index is defined ,when i only fill out one textbox it will throw an error, but if i fill out all five it works fine. please take a look at y code, the variables in javascript is used for its inout name, the count is for the stop adding of input text when it reach 5
HTML and PHP
<form class="form-horizontal" method= "POST">
<div class="control-group">
<div class="inc">
<div class="controls">
<button style="margin-left: 50px" class="btn btn-info" type="submit" id="append" name="append">
Add Textbox</button>
<br>
<br>
</div>
</div>
<input type="submit" class="btn btn-info" name="submit" value="submit"/>
</div>
<?php
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
if(isset($_POST['submit'])){
for($i=1; $i<=5; $i++){
if(isset($_POST["textbox$i"]) && $_POST["textbox$i"] !=""){
$sasa = $_POST["textbox$i"];
$sql="INSERT into sasa (sasa) values('$sasa')";
echo $sql."<br>";
$q=$conn->query($sql);
}
}
}
?>
javascript;
<script type="text/javascript">
jQuery(document).ready( function () {
var val = 1;
var me = 0;
var count = 0;
$("#append").click( function() {
if(count<5){
if(me==0){
val=1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
else{
val = val + 1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
}
else{
}
});
jQuery(document).on('click', '.remove_this', function() {
me = me - 1;
count = count - 1;
jQuery(this).parent().remove();
return false;
});
});
both your JS and PHP are wrong. You need to post an array rather than naming each textbox. In other words, your textbox names should be something like name='textbox[]'. Redo it like this:
JS:
$(document).ready(function () {
$("#append").click(function (e) {
e.preventDefault();
var textboxes = $(".textbox").length;
if (textboxes < 5) {
$(".inc").append("<div class='controls'>\
<input class='textbox form-control' type='text' name='textbox[]' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
});
});
PHP:
if (isset($_POST['submit'])) {
if (!empty($_POST['textbox'])) {
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
$textboxes = $_POST['textbox'];
foreach ($textboxes as $value) {
$sql = "INSERT into sasa (sasa) values('$value')";
echo $sql . "<br>";
$q = $conn->query($sql);
}
}
}
Ok, it seems like your goal is to send a multidimensional array to PHP. In other words, you want PHP to be able to receive something in this format:
array (size=2)
0 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
1 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
In order for you to achieve this, you need to create a function that indexes your input textboxes when you create them and when you delete them so that you can end up with inputs with indexed name attributes like so:
<input name="data[0][text]">
<input name="data[0][box]">
<input name="data[1][text]">
<input name="data[1][box]">
With that said, this is the JS I would use:
<script>
$(document).ready(function () {
function re_index($cont) {
$cont.find(".textbox_group").each(function (i) {
$(this).find('.text').attr("name", "data[" + i + "][text]");
$(this).find('.box').attr("name", "data[" + i + "][box]");
});
}
$("#append").click(function (e) {
e.preventDefault();
var $cont = $(".inc");
if ($(".textbox_group").length < 5) {
$cont.append("<div class='controls textbox_group'>\
<input class='text form-control' type='text' >\
<input class='box form-control' type='text' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
re_index($cont);
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
var $cont = $(".inc");
re_index($cont);
});
});
</script>
Then in PHP you can capture the data and iterate to insert it with SQL:
$data = $_POST['data'];
foreach ($data as $input) {
var_dump($input['text']);
var_dump($input['box']);
}

Categories