JQuery and PHP - Inserting multiple rows - php

Tried and tried multiple asked questions with solutions here, but all were not solving my problem.
This form uses JQuery to dynamically add a set of fields. The problem is that MySQL does not insert the set of data upon submission. Here is the code:
HTML:
<form action="new_purchase_order%20(1).php" method="post">
Supplier
<select name="supplier[]">
<option value="">Select supplier...</option>
<?php
$get_supps = "select supplier_name from suppliers";
$supplist = mysqli_query($db, $get_supps);
//get suppliers available in the database
while($row = mysqli_fetch_assoc($supplist)) {
?>
<option value="<?php echo $row['supplierID'] ?>"><?php echo $row['supplier_name'] ?></option>
<?php } ?>
</select><br /><br />
<select name="item[]">
<option value="">Select item...</option>
<?php
$get_items = "select name from raw_materials";
$itemlist = mysqli_query($db, $get_items);
//get all raw materials available in the database
while($row = mysqli_fetch_assoc($itemlist)) {
?>
<option value="<?php echo $row['materialID'] ?>"><?php echo $row['name'] ?></option>
<?php } ?>
</select>
<!--enter its unit price-->
<input type="text" name="price[]" placeholder="Unit Price">
<!--enter the qty of the item selected-->
<input type="number" name="qty[]" min=1 placeholder="Qty" width="30px">
ADD
PHP:
<?php
include("session.php");
if (isset($_POST['submit'])) {
$supplier = $_POST['supplier'];
$item = $_POST['item'];
$qty = $_POST['qty'];
$price = $_POST['price'];
for ($i=0; $i < count($item); $i++) {
$supplier[$i] = mysqli_real_escape_string($db, $supplier[$i]);
$item[$i] = mysqli_real_escape_string($db, $item[$i]);
$qty[$i] = mysqli_real_escape_string($db, $qty[$i]);
$price[$i] = mysqli_real_escape_string($db, $price[$i]);
if (count($item) >= 0 && count($item) <= 24) {
mysqli_query($db, "insert into purchase_order_history values('', '{$item[$i]}', '{$qty[$i]}', '{$price[$i]}', '', '$supplier[$i]', 'Pending')");
echo "Success";
}
else {
echo "Error";
}
}
}
?>
Basically it uses the arrays of item, qty, and price. My problem is that it doesn't insert anything at all despite no errors to the PHP. The query is:
insert into purchase_order_history values('', '{$item[$i]}', '{$qty[$i]}', '{$price[$i]}', '', '$supplier[$i]', 'Pending');
EDIT: Here's the JQuery code:
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Bootstrap js library -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
//group add limit
var maxGroup = 24;
//add more fields group
$(".addMore").click(function(){
if($('body').find('.form').length < maxGroup){
var fieldHTML = '<div
class="form">'+$(".formCopy").html()+'</div>';
$('body').find('.form:last').after(fieldHTML);
}else{
alert('Only '+maxGroup+' items are allowed.');
}
});
//remove fields group
$("body").on("click",".remove",function(){
$(this).parents(".form").remove();
});
});
</script>
Is there an error with the query itself? Or is it the array coding that causes the problem?

Related

Populating Second Dropdown Based on first dropdown from the database table without using javascript

I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>

How to obtain the option selected from the drop down menu and insert it into a mysql table

I've been trying to do a dynamic drop down menu using php/mysql with ajax. But I'm new to php and ajax so i don't know how to insert the selected option into a mysql table. I created a form where the action leads to a insertsql.php file but its not working.I'm using wamp server. Any help would be greatly appreciated.
index1.php
<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "projects");
$pname = '';
$query = "SELECT pname FROM project_details GROUP BY pname ORDER BY pname ASC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$pname .= '<option value="'.$row["pname"].'">'.$row["pname"].'</option>';
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>zz
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Dynamic Dependent Select Box using JQuery Ajax with PHP</h2><br /><br />
<form method = "POST" action = "insertsql.php" >
<select name="pname" id="pname" class="form-control action">
<option value="">Select Project</option>
<?php echo $pname; ?>
</select>
<br />
<select name="user" id="user" class="form-control action">
<option value="">Select User Name</option>
</select>
<br />
<input type="submit" name="update" value="Update">
<p id="dem"></p>
<p id="demo"></p>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "pname")
{
result = 'user';
}
$.ajax({
url:"fetch.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
</script>
fetch.php
<?php
//fetch.php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("localhost", "root", "", "projects");
$output = '';
if($_POST["action"] == "pname")
{
$query = "SELECT fname,lname FROM users WHERE pname = '".$_POST["query"]."' GROUP BY fname";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select User</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["fname"].' '.$row["lname"].'">'.$row["fname"]." ".$row["lname"].'</option>';
}
}
echo $output;
}
?>
insertsql.php
<?php
include('sqlconfig.php');
$pname= $_POST['pname'];
$username=$_POST['user'];
$date=$_POST['wdate'];
$hours=$_POST['hours'];
echo "$pname";
echo "<br>$username<br>";
$sql="INSERT INTO worklogging(pname,username,wdate,wkhours) VALUES ('$pname','$username','$date','$hours')";
if(!mysqli_query($con,$sql))
{echo 'not inserted';}
else
{echo 'Inserted';
}
?>
This is the part where the data from the dropdown menu is inserted into the mysql table. Thank you all for the help :)

Insert values into database from form with drop downs

I am trying to insert values input from the user in a form into my database.
I have 2 drop down lists for a blood test and then category. E.g user first selects drop down 1 'Thyroid' (Category) and then drop down 2 displays 'FT4,FT3 TSH' (blood test) etc and the user makes their selection.
Then they input the date and the value.
In my insert I need to insert into my database the user_id(established after login with session variables, bloodtest_id(from drop down 2), date, value.
I can't get my SQL query right for the insert in general and need some help please.
Drop down 2 (blood test) is in a seperate php file and I'm not sure how to tell the SQL query how to find that value to use either?
The addBlood.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM category");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Category and Test</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getTest(val) {
$.ajax({
type: "POST",
url: "get_test.php",
data:'category_id='+val,
success: function(data){
$("#test-list").html(data);
}
});
}
function selectCategory(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Category:</label><br/>
<select name="category" id="category-list" class="demoInputBox" onChange="getTest(this.value);">
<option value="">Select Category</option>
<?php
foreach($results as $category) {
?>
<option value="<?php echo $category["category_id"]; ?>"><?php echo $category["category_name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
//$currentBloodTest=$test["bloodtest_id"];
$currentUser=$_SESSION["currentUserID"];
$value = $_POST['result'];
$date = $_POST['date'];
//$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id,date,value)values ($currentUser,$currentBloodTest, $date , $value)");
$dbParams = array();
$query->execute($dbParams);
echo "<br><br><span>Data Inserted successfully...!!</span>";
}
?>
</body>
</html>
Below is the getTest.php which gets all the blood tests.
<?php
include('dbConnect.php');
if(!empty($_POST["category_id"])) {
$queryStr=("SELECT * FROM bloodtests WHERE category_id = '" . $_POST["category_id"] . "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select Test</option>
<?php
foreach($results as $test) {
?>
<option value="<?php echo $test["bloodtest_id"]; ?>"><?php echo $test["test_name"]; ?></option>
<?php
}
}
?>
If this is where you are having some troubles, and are unsure how to proceed:
//$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id,date,value)
// VALUES ($currentUser,$currentBloodTest, $date , $value)");
$dbParams = array();
$query->execute($dbParams);
Then this may help you out (you were very close):
$currentUser = $_SESSION["currentUserID"];
$currentBloodTest = $_POST['test']; // name of the 'select' element
$value = $_POST['result'];
$date = $_POST['date'];
$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id, date, value)
VALUES (?, ?, ?, ?)");
$query->execute( array($currentUser, $currentBloodTest, $date, $value) );
Also, this part you have in the ajax lookup:
$queryStr=("SELECT * FROM bloodtests WHERE category_id = '" . $_POST["category_id"] . "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
Really should be written as:
$queryStr = "SELECT * FROM bloodtests WHERE category_id = ?";
$results = $db->prepare($queryStr);
$results->execute( array($_POST["category_id"]) );

How to Display Option Name in Dropdown using Javascript

I have two dropdowns which values are populated from MySQL. The second dropdown values depends on the first dropdown option.
Anyways, the code is working. Now using my code I am posting hospital_id to another php. But I want to display hospital_name as text on the dropdown as well, but as of now I am only able to display the hospital_id.
Please see me code below and suggest me a solution:
$query = "SELECT bp_id,bp_name FROM mfb_billing";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']);
}
$query = "SELECT bp_id, hospital_id, hospital_name FROM mfb_hospital";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_id']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
This is the script:
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 1; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].bp_id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].hosp);
}
}
</script>
This is my form:
<body onload='loadCategories()'>
<form id="reportvalue" action="testpj2.php" method="post">
<select id='categoriesSelect'>
<option value="1">Select Billing Provider</option>
</select>
<select name='hospitalname[]' id='subcatsSelect' multiple='multiple'>
<option value="all">Select Billing Provider</option>
</select>
<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to">
<?php
//$a = $_REQUEST['hospitalname[]'];
//echo $a;
?>
<input type="submit" name="Submit" value="Submit">
</form>
HTML
<select id="someId"></select>
Javascript
document.getElementById('someId').innerHTML="
<option value='value1'>"+option1+"</option>
<option value='value2'>"+option2+"</option>
<option value='value3'>"+option3+"</option>";
Update:
for dynamic data from SQL query,
Try putting these codes after query execution. replace $row['value'] and $row['option'] with the respected dynamic values.
echo"<script type='text/javascript'> var str = '' </script>";
while($row = $result->fetch_assoc())
{
echo"<script type='text/javascript'>
str = str + '<option value='+".$row['value']."+'>'+".$row['option']."+'</option>
</script>";
}
echo"<script type='text/javascript'>
document.getElementById('someId').innerHTML = str
</script>";
if you are getting the hospital id then it is very easy to populate the selected value by getting it through from mysql
$query = "SELECT hospital_id, hospital_name FROM mfb_hospital where hospital_id = '$_post['hospital_id']'";
$result = $db->query($query);
$res = mysql_fetch_array($result)
In your select option value code put this code
<option value="your ids here will populate" <?php if($hospital_array['hospital_id']==$res['hospital_id']) echo "selected=selected" ?>>Your hospital name will display here which you selected</option>

change dropdown from array to check box

I would like a change from the drop down to the checkbox, I want to change it because I want firstly select the list in the array can be selected before store to database via the checkbox, so the dropdown script was as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1">
<select name="from">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<option value="<?php echo $key; ?>" selected="selected"><?php echo $stock; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $stock; ?></option>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Convert">
</form>
and i Changed it to the checkbox as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1"><input type="submit" name="submit" value="Convert">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>" checked="checked"><?php echo $stock; ?>
<?php
}
else
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>"><?php echo $stock; ?>
<?php
}
}
?>
</form>
but does not work, am I need to display Other codes related?
Thanks if some one help, and appreciated it
UPDATED:
ok post the first apparently less obvious, so I will add the problem of error
the error is
Fatal error: Call to undefined method st_exchange_conv::convert() in C:\xampp\htdocs\test\do.php on line 21
line 21 is $st->convert($from,$key,$date);
session_start();
if(isset($_POST['submit']))
{
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
Why I want to change it from dropdown to checkbox?
because with via checkbox list I will be able to choose which ones I checked it was the entrance to the database, then it seem not simple to me, I looking for some help< thanks So much For You mate.
You have not removed the opening <select> tag.
But you removed the <submit> button.
You changed the name from "from" to "from[]".
EDIT: After your additions:
Using the dropdown list you were only able to select one value for from. Now you changed it to checkboxes and thus are able to select multiple entries. This results in receiving an array from[] in your script in do.php. Your functions there are not able to handle arrays or multiple selections in any way.
You have to re-design do.php, change your form back to a dropdown list or use ratio buttons instead.

Categories