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);
}
}
Related
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.
Question.php
<?php
include 'Pre-function.php'
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="CSS/Start.css">
</head>
<body>
<div class="nav">
Home
News
Contact
</div>
<div class="question">
<div class="A4">
<form action="Answer.php" method="post">
<?php getQuestion($conn); ?>
<input type="submit" name="Submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
Its html page to ask question
Pre-function.php
<?php
include 'conn.php';
function getQuestion($conn) {
$query = "SELECT * FROM question ";
$result = mysqli_query($conn, $query);
if($result){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$question_id = $row['question_id'];
$question_body = $row['question_body'];
$option_a = $row['option_a'];
$option_b = $row['option_b'];
echo '
<h2 class="qtitle">'.$question_body.'</h2>
<label for='.$question_body.'>Yes</label>
<input type="radio" name="'.$question_id.'" value="Yes">
<input type="hidden" name="option_a" value="'.$option_a.'">
<label for="'.$question_body.'">No</label>
<input type="radio" name="'.$question_id.'" value="No">
<input type="hidden" name="option_b" value="'.$option_b.'">
<input type="hidden" name="submitted" value="submitted"><hr>';
}
}
}
?>
Basically this form asked question whether yes or no using radio button. $option_a == 'Yes' and $option_b == 'No'. The question is like this "Are you have fever ?". So when i submit the value did not pass to the 'Answer.php' page.
'Answer.php' page.
<?php
include 'conn.php';
if(isset($_POST['Submit']) && !empty($_POST['Submit'])){
echo $_POST['option_a'];
echo 'succeed';
}
else{
echo 'no data';
}
?>
In this page have error undefined_index value but still echo succeed.
Your HTML code should look like the following:
<input type="radio" name="whatevername" value="Yes">
<input type="hidden" name="whatevername" value="No">
You can use PHP to insert whatever values you want but you need the radio button name to be the same.
Then if you want to echo that in PHP you'd use:
echo $_POST['whatevername']; //same name you used in the form
You are passing value as name for radio buttons
name="'.$option_a.'"
This will result you in name ="Yes"
And you are trying to fetch echo $_POST['option_a']; where option_a is not defined.
Try this
<input type="radio" name="'.$question_id.'" value="Yes">
<input type="hidden" name="option_a" value="'.$option_a.'">
Same for other radio button
Try this one :
<?php
include 'conn.php';
function getQuestion($conn) {
$query = "SELECT * FROM question ";
$result = mysqli_query($conn, $query);
if($result){
echo '<div class="A4">';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$question_id = $row['question_id'];
$question_body = $row['question_body'];
$option_a = $row['option_a'];
$option_b = $row['option_b'];
echo '
<div class="A4">
<h2 class="qtitle">'.$question_body.'</h2>
<form action="Answer.php" method="post">
<label for='.$question_body.'>Yes</label>
<input type="radio" name="radioQuestions[]" value="'.$question_id.'-'.$option_a.'">
<label for="'.$question_body.'">No</label>
<input type="radio" name="radioQuestions[]" value="'.$question_id.'-'.$option_b.'">
<input type="hidden" name="submitted" value="submitted"><hr>';
}
echo'
<input type="submit" name="Submit" value="Submit">
</form>
</div>';
}
}
?>
<?php
include 'conn.php';
if(isset($_POST['submitted']) && !empty($_POST['submitted'])){
$questionAndOptions = $_POST['radioQuestions'];
foreach ($questionAndOptions as $questionAndOption) {
$arrQuestionAndOption = explode("-", $questionAndOption);
echo $arrQuestionAndOption[0]; //question
echo $arrQuestionAndOption[1]; //option
}
echo 'succeed';
}
else{
echo 'no data';
}
?>
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 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 }
?>
I am new to PHP and want to create a form where the user inserts data into the form (which works) and then that gets stored on MYSQL DB (that works), now the data has to be displayed and then must be able to modify certain records, now I have the part where the records shows and also the "edit" button, but something went wrong somewhere as the same record keeps appearing, so I guess something is wrong with my code :(
Please help:
Here is the index.php code:
<?php
include('dbinfo.php');
$sql="SELECT * FROM stats";
$result = mysql_query($sql, $db) or die (mysql_error());
$pageTitle = "My Stats Database";
include("header.php");
print <<<HERE
<h2> My Contacts</h2>
Select a Record to update add new stat.
<table id="home">
HERE;
while ($row=mysql_fetch_array($result)){
$id=$row["id"];
$type=$row["type"];
$depthead=$row["depthead"];
$person=$row["person"];
$descr=$row["descr"];
$recdate=$row["recdate"];
$tolog=$row["tolog"];
$senttorev=$row["senttorev"];
$recfromrev=$row["recfromrev"];
print <<<HERE
<tr>
<td>
<form method="POST" action="updateform.php">
<input type="hidden" name="sel_record" value="$id">
<input type="submit" name="update" value=" Edit " </form>
</td>
<td><strong> Description: </strong>$descr,<p> <strong>Type: </strong>$type</p> <p><strong> Department Head: </strong>$depthead</p>
<strong> Test Analyst: </strong> $person<br/></td>
HERE;
}
print "</tr></table></body></html>";
?>
Then here is my update updateform.php script:
<?php
include("dbinfo.php");
$sel_record = $_POST['sel_record'];
//$sel_record = (isset($_POST['sel_record'])) ? $_POST['sel_record'] : '';
$sql = "SELECT * FROM stats WHERE id = 'sel_record'";
//execute sql query and get result
$result = mysql_query($sql, $db) or die (mysql_error());
if (!$result) {
print "<h1> Something went wrong!</h1>";
} else
{ //begin while loop
while ($record = mysql_fetch_array($result, MYSQL_ASSOC)){
$id = $record["id"];
$type = $record['type'];
$depthead = $record['depthead'];
$person = $record["person"];
$descr = $record["descr"];
$recdate = $record["recdate"];
$tolog = $record["tolog"];
$senttorev = $record["senttorev"];
$recfromrev = $record["recfromrev"];
}
}
//end while loop
$pagetitle = "Edit Stat";
include ("header.php");
print <<<HERE
<h2> Modify this Stat</h2>
<p> Change the values in the boxes and click "Modify Record" button </p>
<form id="stat" method="POST" action="update.php">
<input type="hidden" name="id" value="$id">
<div>
<label for="type">Type*:</label>
<input type="text" name="type" id="type" value="$type">
</div>
<p>
</p>
<div>
<label for = "depthead" >Department Head*:</label>
<input type = "text" name = "depthead" id = "depthead" value = "$depthead">
</div>
<p>
</p>
<div>
<label for="person">Test Analyst*:</label>
<input type="text" name="person" id="person" value="$person">
</div>
<p>
</p>
<div>
<label for="descr">Description*:</label>
<input type="text" name="descr" id="descr" value="$descr">
</div>
<p>
</p>
<div>
<label for="recdate">Date Received*:</label>
<input type="text" name="recdate" id="recdate" value="$recdate">
</div>
<p>
</p>
<div>
<label for="tolog">Date to log*:</label>
<input type="text" name="tolog" id="tolog" value="$tolog">
</div>
<p>
</p>
<div>
<label for="senttorev">Sent to Rev:</label>
<input type="text" name="senttorev" id="senttorev" value="$senttorev">
</div>
<p>
</p>
<div>
<label for="recfromrev">Received from Rev*:</label>
<input type="text" name="recfromrev" id="recfromrev" value="$recfromrev">
</div>
<p>
</p>
<div id="mySubmit">
<input type="submit" name="submit" value="Modify Record">
</div>
</form>
HERE;
?>
And then the actual updating of the mysql has an update.php script:
<?php
include "dbinfo.php";
$id = $_POST['id'];
$type = $_POST['type'];
$depthead = $_POST['depthead'];
$person = $_POST['person'];
$descr=$_POST['descr'];
$recdate=$_POST['recdate'];
$tolog=$_POST['tolog'];
$senttorev=$_POST['senttorev'];
$recfromrev=$_POST['recfromrev'];
$sql="UPDATE stats SET
depthead='$depthead',
person='$person',
descr='$descr',
recdate='$recdate',
tolog='$tolog',
senttorev='$senttorev',
recfromrev='$recfromrev'
WHERE id='$id'";
$result=mysql_query($sql) or die (mysql_error());
print "<html><head><title>Update Results</titlel></head><body>";
include "header.php";
print <<<HERE
<h1>The new Record looks like this: </h1>
<td>
<p><strong>Type: </strong>$type</p>
<p><strong>Department Head: </strong>$depthead</p>
<p><strong>Test Analyst: </strong> $person</p>
<p><strong>Description: </strong>$descr</p>
<p><strong>Received Date:</strong>$recdate</p>
<p><strong>Date to Log:</strong>$tolog</p>
<p><strong>Sent to rev:</strong>$senttorev</p>
<p><strong>Received from Rev:</strong>$recfromrev</p>
<br/>
HERE;
Can someone please tell me why only one of the records keeps appearing doesn't matter which one I select from my index.php page. For some reason I think it is my $sel_record variable, but I am not sure and have run out of Ideas..
Thank you in advance..
Here's your issue in updateform.php:
$sql = "SELECT * FROM stats WHERE id = 'sel_record'";
That should be:
$sql = "SELECT * FROM stats WHERE id = $sel_record";
You missed out the $ symbol to call a variable, and you don't need quotation marks around an ID.