submit button doesnt work - php

I have this piece of code that i cant get the submit button to work properly
please help me. I have prepared 3 buttons which i havent worked on the action yet. But the button doesnt work even when i Just want to echo something
<?php
require_once '../dbinfo.inc.php';
session_start();
// CHECK IF THE USER IS LOGGED ON ACCORDING
// TO THE APPLICATION AUTHENTICATION
if(!isset($_SESSION['username'])){
echo <<< EOD
<h1>You are UNAUTHORIZED !</h1>
<p>INVALID usernames/passwords<p>
<p>LOGIN PAGE<p>
EOD;
exit;
}
// GENERATE THE APPLICATION PAGE
$conn = oci_pconnect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB);
// 1. SET THE CLIENT IDENTIFIER AFTER EVERY CALL
// 2. USING UNIQUE VALUE FOR BACK END USER
oci_set_client_identifier($conn, $_SESSION['username']);
$username = htmlentities($_SESSION['username'], ENT_QUOTES);
if (isset($_POST["ajax"]) && $_POST["ajax"] == 1){
$sql = "SELECT QTY FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$cutting_sql = "SELECT CUTTING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$assembly_sql = "SELECT ASSEMBLY FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$welding_sql = "SELECT WELDING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$drilling_sql = "SELECT DRILLING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$finishing_sql = "SELECT FINISHING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$stid = oci_parse($conn, $sql);
$stid_cutting = oci_parse($conn, $cutting_sql);
$stid_assembly = oci_parse($conn, $assembly_sql);
$stid_welding = oci_parse($conn, $welding_sql);
$stid_drilling = oci_parse($conn, $drilling_sql);
$stid_finishing = oci_parse($conn, $finishing_sql);
// The defines MUST be done before executing
oci_define_by_name($stid, 'QTY', $qty);
oci_execute($stid);
oci_define_by_name($stid_cutting, 'CUTTING', $cutting);
oci_execute($stid_cutting);
oci_define_by_name($stid_assembly, 'ASSEMBLY', $assembly);
oci_execute($stid_assembly);
oci_define_by_name($stid_welding, 'WELDING', $welding);
oci_execute($stid_welding);
oci_define_by_name($stid_drilling, 'DRILLING', $drilling);
oci_execute($stid_drilling);
oci_define_by_name($stid_finishing, 'FINISHING', $finishing);
oci_execute($stid_finishing);
// Each fetch populates the previously defined variables with the next row's data
oci_fetch($stid);
oci_fetch($stid_cutting);
oci_fetch($stid_assembly);
oci_fetch($stid_welding);
oci_fetch($stid_drilling);
oci_fetch($stid_finishing);
//echo quantity to the screen
echo "<b><font size='10'>".$qty."</font></b></br>";
if ($cutting == $qty){
echo "<p><b><font color='#FF8566' size='5'>CUTTING COMPLETED</font></b></p>";
} else {
$maxcutting = $qty - $cutting;
echo "<input id='cutting' name='cutting' type='number' min = '0' max = '$maxcutting' placeholder='CUTTING PROGRESS TODAY' class='input'/>";
}
if ($assembly == $qty){
echo "<p><b><font color='#FF8566' size='5'>ASSEMBLY COMPLETED</font></b></p>";
} else {
$maxassembly = $qty - $assembly;
echo "<input id='assembly' name='assembly' type='number' min = '0' max = '$maxassembly' placeholder='ASSEMBLY PROGRESS TODAY' class='input'/>";
}
if ($welding == $qty){
echo "<p><b><font color='#FF8566' size='5'>WELDING COMPLETED</font></b></p>";
} else {
$maxwelding = $qty - $welding;
echo "<input id='welding' name='welding' type='number' min = '0' max = '$maxwelding' placeholder='WELDING PROGRESS TODAY' class='input'/>";
}
if ($drilling == $qty){
echo "<p><b><font color='#FF8566' size='5'>DRILLING COMPLETED</font></b></p>";
} else {
$maxdrilling = $qty - $drilling;
echo "<input id='drilling' name='drilling' type='number' min = '0' max = '$maxdrilling' placeholder='DRILLING PROGRESS TODAY' class='input'/>";
}
if ($finishing == $qty){
echo "<p><b><font color='#FF8566' size='5'>FINISHING COMPLETED</font></b></p>";
} else {
$maxfinishing = $qty - $finishing;
echo "<input id='finishing' name='finishing' type='number' min = '0' max = '$maxfinishing' placeholder='FINISHING PROGRESS TODAY' class='input'/>";
}
echo '<section></br></br></br>';
echo ' <input type="submit" value="SUBMIT PROGRESS" class="button red" />';
echo ' <input type="reset" value="RESET FIELDS" class="button" /></br>';
echo ' <input type="submit" value="GO TO PAINTING" name="paint" class="button green" /></section>';
die;}
if (isset($_POST['submit'])){
echo $cutting;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title> Update Fabrication Progress</title>
<link type="text/css" rel="stylesheet" href="../css/goldenform/golden-forms.css"/>
<link type="text/css" rel="stylesheet" href="../css/goldenform/font-awesome.min.css"/>
<script type="text/javascript">
function OnSelectionChange (select) {
var selectedOption = select.options[select.selectedIndex];
//some ajax checkpoint
//alert ("The selected option is " + selectedOption.value);
jQuery.ajax({
url: location.href,
data: {'hm':selectedOption.value, 'ajax':1},
type: "POST",
success: function( data ) {
jQuery("#lbl_qty").html(data);//PRINT QTY TO THE SCREEN
}
});
//some ajax checkpoint
//alert('after ajax');
}
</script>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body class="bg-wooden">
<div class="gforms">
<div class="golden-forms wrapper">
<form>
<div class="form-title">
<h2>FABRICATION UPDATE</h2>
</div><!-- end .form-title section -->
<div class="form-enclose">
<div class="form-section">
<fieldset>
<legend>&nbsp Select HEADMARK and the details will be shown <span class="bubble blue">1</span></legend>
<section>
<div class="row">
<div class="col4 first">
<label for="headmark" class="lbl-text tleft">HEADMARK :</label>
</div><!-- end .col4 section -->
<div class="col8 last">
<!-- POPULATED DROPDOWN LIST FROM THE DB -->
<label for="headmark" class="lbl-ui select">
<?php
$sql_hm_comp = 'SELECT HEAD_MARK FROM FABRICATION';
$result = oci_parse($conn, $sql_hm_comp);
oci_execute($result);
echo '<SELECT name="headmark" id="headmark" onchange="OnSelectionChange(this)">'.'<br>';
echo '<OPTION VALUE=" ">'."".'</OPTION>';
while($row = oci_fetch_array($result,OCI_ASSOC)){
$HM = $row ['HEAD_MARK'];
echo "<OPTION VALUE='$HM'>$HM</OPTION>";
}
echo '</SELECT>';
?>
</label>
</div>
</div>
</section><!-- END OF DROPDOWN LIST -->
<section>
<div class="row">
<div class="col4 first">
<label for="lnames" class="lbl-text tleft">Total Quantity:</label>
</div>
<div class="col8 last">
<!-- VALUE PASSED FROM AJAX PROCESSING -->
<label id='lbl_qty' class='lbl-ui'><font size='3'> </font></label>
</div>
</div>
</section>
</div><!-- end .form-section section -->
</div><!-- end .form-enclose section -->
<div class="form-buttons">
</div><!-- end .form-buttons section -->
</form>
</div><!-- end .golden-forms section -->
</div><!-- end .gforms section -->
<div></div><!-- end section -->
<div></div><!-- end section -->
</body>
</html>

Welcome to SO!
I found two small errors, I think it will do the trick:
Add post method to the form: <form method="post">
Add name attribute at least to one submit button:
<input type="submit" name="submit" value="SUBMIT PROGRESS" class="button red" />
Additionally it is recommended to use JS to determine which submit button has been clicked. For example you can add a hidden element, and modify its value:
echo '<input type="submit" value="GO TO PAINTING" ... onclick="$(\'[name=submit_clicked]\').val(\'no\');" />...';
...
<form method="post">
<input type="hidden" name="submit_clicked" value="yes" />
...
</form>

Related

How do I pass these variables to another php file

I'm currently making a shopping website and I need to be able to pass two variables to the next page, the code may be badly written because I'm new to this, but I'm trying to pass the number from the drop-down menu and the "row['pid']" to another page. As shown below I have attempted to use a form button but it can only transfer the number from the dropdown. There is database connected so if you try to load it up, it may not load anything. This issue is specifically focussing on the button which the form is linked to at the end. Thank you for your time.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://kit.fontawesome.com/9114d9acc8.js" crossorigin="anonymous">
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="includes/navbar/navbar.css">
<link rel="stylesheet" href="css/style.css">
<title>Document</title>
</head>
<body>
<?php include "includes/navbar/navbar.php"; ?>
<div id="arranging">
<?php
require 'includes/dbh.php';
$query = sprintf('SELECT * FROM produce');
$result = mysqli_query($conn, $query);
//$var_value = 'hello';
//$_SESSION['varname'] = $var_value;
while ($row = mysqli_fetch_assoc($result)) {
if ($row['Quantity'] == 0) {
}
else {
?>
<div class="itemTemplate">
<a id="title" onclick="ContentPage(<?php echo $row['pid']; ?>)"><?php echo $row['Name'] ?></a>
<a onclick="ContentPage(<?php echo $row['pid']; ?>)" id="myid"><img src="<?php echo $row['img'] ?>"
alt="<?php echo $row['Name'] ?>"></a>
<span>Price: £<?php echo $row['Price'] ?></span>
<form action="includes/quickBasket.php" method="POST">
<div class="flex-b">
<label for="">Quantity:</label>
<select name="quantity">
<?php
if ($row['Quantity'] > 8) {
for ($x = 1; $x <= 8; $x++) {
echo "<option value='$x'>$x</option>";
}
}
else {
for ($x = 1; $x <= $row['Quantity']; $x++) {
echo "<option value='$x'>$x</option>";
}
}
?>
</select>
<button id="button" type="submit" name="cart" class="fas fa-shopping-basket"></button>
</div>
</form>
</div>
<?php
}
}
?>
</div>
<script>
function ContentPage(elem) {
location.href = "Product.php" + "?id=" + elem;
};
</script>
</body>
</html>
If you want to transfer the PID when the form is submitted then you need a field for it within the form, e.g. a hidden field like this:
<input type="hidden" name="pid" value="<?php echo $row['pid']; ?>"/>
Then when you submit the form, it will be accessible as $_POST["pid"] (just like the value from the dropdown is accessible as $_POST["quantity"]).
This applies to any value - if you want it to be submitted with the form, then there needs to be a proper field for it within the form (or least associated with the form via the necessary attribute).

How to use a dropdown to assign a value to a certain row (out of rows that are being inserted in same form) using PHP

I am creating a quiz builder using SQL, HTML and PHP, whereby the user can insert their question and four answer choices for that question (A, B, C or D).
In the same form they can then choose what choice will be the correct answer from a dropdown. This should then assign the 'is correct' boolean value of that certain answer row to 1 in the database.
[my database structure and what my form should look like is attached]
<?php
include ("nav.php");
include("connect.php");
$quiz_id = htmlentities($_GET["quizid"]);
$quiz = "SELECT * FROM `q_quiz` WHERE q_quiz.id ='$quiz_id'";
$quizresult= $conn->query($quiz);
if(!$quizresult){
echo $conn->error;
}
?>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="ui/styles.css">
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/css/uikit.min.css" />
<!-- UIkit JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/js/uikit-icons.min.js"></script>
</head>
<body>
<div class ='uk-container'>
<?php
if (isset($_POST['submit'])) {
include("connect.php");
$newquest = $conn->real_escape_string($_POST['question']);
$insertquest = "INSERT INTO q_questions(quiz_id, question)
VALUES ('$quiz_id', '$newquest')";
$resultquest = $conn->query($insertquest);
$quest_id = $conn -> insert_id;
if (!$resultquest) {
echo $conn->error;
}
foreach ($_POST['ans'] as $ans) {
$answers = $conn->real_escape_string($ans);
$insertans = "INSERT INTO q_answers (question_id, answer) VALUES ('$quest_id', '$answers')";
$resultans = $conn ->query($insertans);
if (!$resultans) {
echo $conn->error;
} else {
header("Location: managequiz.php?quizid=$quiz_id");
}
} //END OF FOREACH LOOP
}
?>
<?php
while ($row = $quizresult->fetch_assoc()) {
$titledata = $row["title"];
}
?>
<div uk-grid>
<form class="uk-form-horizontal" method='POST' action='#'>
<input type='hidden' name='questionid' value=''>
<fieldset class="uk-fieldset">
<legend class="uk-legend">New question for quiz: <?php echo $titledata?></legend>
<div class="uk-margin">
<label class="uk-form-label">Question</label>
<div class="uk-form-controls">
<textarea class="uk-textarea" rows="5" placeholder="Enter your question here..." name='question' required></textarea>
</div>
</div>
<div class="uk-margin">
<div class="uk-form-label">A</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">B</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">C</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">D</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">Correct Answer:</div>
<div class="uk-form-controls">
<select class="uk-select" id="form-stacked-select">
<option value=''>A</option>
<option value=''>B</option>
<option value=''>C</option>
<option value=''>D</option>
</select>
</div>
<div uk-form-custom>
<input class="uk-button uk-button-default" type="submit" name='submit' tabindex="-1" value='Save & Continue'>
</div>
</div>
</fieldset>
</form>
</div>
</body>
</html>
as kiks73 mentioned, you can assign values to the option of the Select and POST the selected one to your database as correct answer ID.
<html>
<select class="uk-select" id="form-stacked-select" name="correctAnswer">
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
<option value='4'>D</option>
</select>
</html>
If you select A, the value "1" would be sent to your database as correct answer (as long as you correct the SQL part in your php.
EDIT:
I got your question a bit late, sorry.
you need to POST the select aswell in order to get the nessecary information about the correct answer. You could try something like that:
<?php
//just a counter
$i = 1;
//correct boolean 1 or 0
$bool = 0;
if (isset($_POST['submit'])) {
include("connect.php");
$newquest = $conn->real_escape_string($_POST['question']);
$insertquest = "INSERT INTO q_questions(quiz_id, question)
VALUES ('$quiz_id', '$newquest')";
$resultquest = $conn->query($insertquest);
$quest_id = $conn -> insert_id;
if (!$resultquest) {
echo $conn->error;
}
foreach ($_POST['ans'] as $ans) {
//get the value of the selected answer
$correctAnswer = $_POST['correctAnswer'];
//check if the selected one matches with our counter
if($i == $correctAnswer)
{
$bool = 1;
}
else
{
$bool = 0;
}
$answers = $conn->real_escape_string($ans);
$insertans = "INSERT INTO q_answers (question_id, answer, correct) VALUES ('$quest_id', '$answers', $bool)";
$resultans = $conn ->query($insertans);
if (!$resultans) {
echo $conn->error;
} else {
header("Location: managequiz.php?quizid=$quiz_id");
}
$i ++;
} //END OF FOREACH LOOP
}
?>
If you POST the whole form, you can use anything in it. i made an ugly loop, which checks each time you instert an answer to your SQL DB, if this one is selected.

change and delete selected items from list - PHP

I have built a website which has lots of lists/tables (based on php). I am trying to make a Change All and Delete All system for the lists. I have already added checkbox to all individual list items. I also have one checkbox to select all those items with one click. Now I am stuck at how to execute the change and delete option. It's been 3 days...
I have done the Change All code right. But I can't figure out Delete All part.
I don't know to pass the $targetpage variable to make it redirect after that.
Here is the code:
<!DOCTYPE html>
<html>
<title>List 1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3-theme-purple.css">
<?php include('dbcon.php');?>
<style>a {text-decoration: none;}</style>
<!--Select All-->
<script>
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
</script>
<body>
<!--?php include ('header.php');?-->
<form name="form1" enctype="multipart/form-data" action="ajaxAction.php" method="post">
<div class="w3-container">
<div class="w3-padding-32 w3-center">
<input class="w3-btn w3-green" type="submit" name="chkbox" value="Change All" />
<input class="w3-btn w3-red" type="submit" value="Delete All">
</div>
<center>
<table class="w3-table-all" style="width: auto;">
<tr class="w3-theme">
<th><input class="w3-check" type="checkbox" onchange="checkAll(this)" name="chk[]" /></th>
<th>Data</th>
</tr>
<tr>
<td>
<input class="w3-check" type="checkbox" name="chkbox[]" />
</td>
<td class="w3-small" >
The data is displayed here.
</td>
</tr>
</table>
</center>
</div>
</form>
<br>
<!--?php include ('footer.php');?-->
</body>
</html>
Here is the ajaxAction.php code:
<!--Change-->
<?php
if ($_REQUEST['chkbox']) {
$targetpage = $_REQUEST['targetpage'];
$change = array ();
$change = $_REQUEST['chkbox'];
for($c=0;$c<count($change); $c++){
$sql_all = "update `table` set `value`='123' WHERE `id` = '$change[$c]'";
mysql_query($sql_all) or die(mysql_error());
}
?>
<script>
var targetpage = "<?php echo $targetpage ?>";
location.href=targetpage+"?done";
</script>
<?php } ?>
<!--Delete-->
<?php ?>
<script>
var targetpage = "<?php echo $targetpage ?>";
location.href=targetpage+"?done";
</script>
With my current code, I am only able to use the selected array chkbox[] for one processing i.e. Change All. I don't know how to use the same array for Delete All button.
After using the trial and error method and trying for two weeks, I finally got the solution ON MY OWN and I have a serious gripe because no one from this forum cared to show me the solution.
It was simple. All I had to do was to use $_POST instead of $_REQUEST and use different names both the buttons like this:
<input class="w3-btn w3-green" type="submit" name="submit1" value="Change All">
<input class="w3-btn w3-red" type="submit" name="submit2" value="Delete All">
So, I changed ajaxAction.php to:
<?php
//Change All
if(isset($_POST['submit1'])){
if(!empty($_POST['chkbox'])){
$targetpage = $_REQUEST['targetpage'];
foreach($_POST['chkbox'] as $selected){
$sql_all = "update `table` set value='123' WHERE `id` = '$selected'";
mysql_query($sql_all) or die(mysql_error());
}
}
?>
<script>
location.href="tables.php?done";
</script>
<?php } ?>
<?php
//Delete All
if(isset($_POST['submit2'])){
if(!empty($_POST['chkbox'])){
foreach($_POST['chkbox'] as $selected){
$sql_all = "DELETE FROM `table` WHERE `id` = '$selected'";
mysql_query($sql_all) or die(mysql_error());
}
}
?>
<script>
location.href="tables.php?done";
</script>
<?php } ?>
All you had to do was tell me that I should use $_POST. No one from Stack Overflow helped me.

when try to add more field and select then its conflict first row

When i am trying to select option value form row one there's no problem but if i add more and select optional value in second row then its getting conflict first. Every time when you select optional value then only first row conflict i want first row change while changing first select option . Second row select change only second row values.
index.php
<?php
if(!empty($_POST["save"])) {
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$itemCount = count($_POST["item_name"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(!empty($_POST["item_name"][$i]) || !empty($_POST["item_price"][$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_name"][$i] . "', '" . $_POST["item_price"][$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
$result = mysql_query($sql);
if(!empty($result)) $message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
function addMore() {
$("<DIV>").load("input.php", function() {
$("#product").append($(this).html());
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php if(isset($message)) { echo $message; }?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index:item_index},`
success:function(result){
alert(result);
$('#div1').html(result);
}
});
}
</script>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV class="float-left"><select name="item_index" id="item_index" class="required input-small" onchange="salesdetail(this.value);" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$result = mysql_query("select * from item");
while($row=mysql_fetch_assoc($result))
{
echo "<option>".$row['item_name']."</option>";
}
?>
</select>
</DIV>
<DIV class="float-left" id="div1"><input type="text" id="unit_price" name="unit_price" /></DIV>
</DIV>
and getsaleinfo.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$supplier= $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
if($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini" value="<?php echo $row['item_price'];?>" >
</div>
<?php }
?>
database
CREATE TABLE IF NOT EXISTS `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_name` varchar(255) NOT NULL,
`item_price` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `item` (`id`, `item_name`, `item_price`) VALUES
(1, 'hello', 21),
(2, 'hi', 22);
try this...
$('body').on('change','#item_index',function() { //works for ajax loaded contents
var id = $("#item_index").val();
var formid = new FormData();
formid.append('item_index',id);
$.ajax({
url : 'getsaleinfo.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formid,
type : 'post',
success : function(data){
alert(result);
$('#div1').html(result);
//document.getElementById("div1").innerHTML=data;
}
});
}
insted of onchange call this will do...
When you change the selection in the dropdown list, it sends the request to the server:
getsaleinfo.php with item_index:'hello'
That executes
select * from item where item_name='hello' (one line)
That sends
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini"
value="<?php echo $row['item_price'];?>" >
</div>
back to the caller.
The javascript puts that whole thing inside #div1 replacing whatever was there.
From what I'm gathering, addMore() is loading the whole of input.php every time and appending it to #product.
First of all that means you're repeated adding the jquery and function definition, but secondly (and the main problem) - each one adds a NEW div with ID=div1.
When you call
$('#div1').html(result)
in your salesdetail function, that just refers to the first one (since according to HTML you can only have one instance of each ID and the others are ignored.
/*------------------------index.php--------------------------*/
<?php
if (!empty($_POST["save"])) {
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$itemCount = count($_POST["item_index"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for ($i = 0; $i < $itemCount; $i++) {
if (!empty($_POST["item_index"][$i]) || !empty($_POST["unit_price"][$i])) {
$itemValues++;
if ($queryValue != "") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_index"][$i] . "', '" . $_POST["unit_price"][$i] . "')";
}
}
$sql = $query . $queryValue;
if ($itemValues != 0) {
$result = mysql_query($sql);
if (!empty($result))
$message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
var cnt = 1;
function addMore() {
$("<DIV>").load("input.php?cnt=" + cnt, function() {
$("#product").append($(this).html());
cnt++;
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item) {
jQuery(':checkbox', this).each(function() {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php
if (isset($message)) {
echo $message;
}
?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
/*------------------------input.php--------------------------*/
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index, item_id)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index: item_index, item_id: item_id},
success: function(result) {
alert(result);
$('#div_' + item_id).html(result);
}
});
}
</script>
<?php $_REQUEST['cnt'] = (isset($_REQUEST['cnt'])) ? $_REQUEST['cnt'] : 0; ?>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_ind[]" id="item_ind_<?php echo $_REQUEST['cnt']; ?>" /></DIV>
<DIV class="float-left"><select name="item_index[]" id="item_index_<?php echo $_REQUEST['cnt']; ?>" class="required input-small" onchange="salesdetail(this.value, '<?php echo $_REQUEST['cnt']; ?>');" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$result = mysql_query("select * from item");
while ($row = mysql_fetch_assoc($result)) {
echo "<option>" . $row['item_name'] . "</option>";
}
?>
</select></DIV>
<DIV class="float-left" id="div_<?php echo $_REQUEST['cnt']; ?>"><input type="text" id="unit_price_<?php echo $_REQUEST['cnt']; ?>" name="unit_price[]" /></DIV>
</DIV>
getsaleinfo.php
/*------------------------getsaleinfo.php--------------------------*/
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$supplier = $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
$_REQUEST['item_id'] = (isset($_REQUEST['item_id'])) ? $_REQUEST['item_id'] : '';
if ($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<input type="text" name="unit_price[]" id="unit_price_<?php echo $_REQUEST['item_id']; ?>" class="input-mini" value="<?php echo $row['item_price']; ?>" >
</div>
<?php }
?>

Dynamic input and add it into a database

Hello everybody, likle my title tells I'm making a dynamic input but I have errors and I'm going to cry haha. Seriously I have difficulties to make it. I want to add dynamic input and add value in my database. Here is my code :
<?php
// Connect to the DB
$link = mysqli_connect("localhost","root","","testlp") or die("Error " . mysqli_error($link));
// store in the DB
if(!empty($_POST['ok'])) {
// first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM recherche WHERE id=$id";
$link->query($sql);
}
}
// adding new recherche
if(!empty($_POST['name'])) {
// ( $i = 0; $i < count($_POST['name']); $i++)
{
$sql = "INSERT INTO recherche (name) VALUES ".$_POST['name'][$i];
$link->query($sql);
}
}
}
// select existing recherche here
$sql="SELECT * FROM recherche ORDER BY id";
$result = $link->query($sql);
?>
<html>
<head>
<title>Simple example of dynamically adding rows with jQuery</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Simple example of dynamically adding rows with jQuery</h1>
<form method="post">
<div id="itemRows">
Item name: <input type="text" name="add_name" /> <input onclick="addRow(this.form);" type="button" value="Add row" /> (This row will not be saved unless you click on "Add row" first)
<?php
// let's assume you have the product data from the DB in variable called $recherche
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</body>
</html>
I've problem in my loop and I get this error :
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
boolean given in C:\wamp\www\testing\dynamic-form-fields.html.php on
line 51 This is the line 51 in the previous code
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;?>
Thanks for support!
EDIT
Here the new part of the code you guys helped me with : but nothing happens when I submit to the database. I checked in phpmyadmin of my database.
<?php
// Connect to the DB
$link = mysqli_connect("localhost","root","","testlp") or die("Error " . mysqli_error($link));
// store in the DB
if(!empty($_POST['ok'])) {
// first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM recherche WHERE id=$id";
$link->query($sql);
}
}
// adding new recherche
if(!empty($_POST['name'])) {
foreach($_POST['name'] as $name)
{
//escape special characters from inputed "name" to prevent SQL injection.
$sql = "INSERT INTO recherche (name) VALUES ".mysqli_real_escape_string($link,$name);
$link->query($sql);
}
}
}
// select existing recherche here
$sql="SELECT * FROM recherche ORDER BY id";
$result = $link->query($sql);
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<form method="post">
<div id="itemRows">
Item name: <input type="text" name="add_name" /> <input onclick="addRow(this.form);" type="button" value="Add row" /> (This row will not be saved unless you click on "Add row" first)
<?php
if($result!=false && mysqli_num_rows($result)>0){
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;
}
?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</body>
</html>
Here finaly are the result with great guys in this forum !
Feel free to edit or make whatever you want with this code!
<?php
// Connect to the DB
$link = mysqli_connect("localhost","root","","testlp") or die("Error " . mysqli_error($link));
// store in the DB
if(!empty($_POST['ok'])) {
// first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM recherche WHERE id=$id";
$link->query($sql);
}
}
// adding new recherche
if(!empty($_POST['name'])) {
foreach($_POST['name'] as $name)
{
//escape special characters from inputed "name" to prevent SQL injection.
$sql = "INSERT INTO recherche (name) VALUES ('".mysqli_real_escape_string($link,$name)."')";
$link->query($sql);
}
}
}
// select existing recherche here
$sql="SELECT * FROM recherche ORDER BY id";
$result = $link->query($sql);
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<form method="post">
<div id="itemRows">
Item name: <input type="text" name="add_name" /> <input onclick="addRow(this.form);" type="button" value="Add row" /> (This row will not be saved unless you click on "Add row" first)
<?php
if($result!=false && mysqli_num_rows($result)>0){
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;
}
?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</body>
</html>
Don't ever assume you have data in $result.test it before processing it.
<?php
if($result!=false && mysqli_num_rows($result)>0){
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;
}
?>
EDIT
FIX THIS PART IN YOUR CODE, to insert multiple rows of form submit
// adding new recherche
if(!empty($_POST['name'])) {
foreach($_POST['name'] as $name)
{
//escape special characters from inputed "name" to prevent SQL injection.
$sql = "INSERT INTO recherche (name) VALUES ('".mysqli_real_escape_string($link,$name)."')";
$link->query($sql);
}
}

Categories