Update mysql with $_POST data from while loop
I'm trying to get this round my head, but i am failing quite hard :[
I have 3 rows in a database which i am echoing out in a while() loop.
A user can change search_terms and then save the fields in mysql, however i don't quite know how to do this, as there are 3 rows, so i can't just do;
<?php
if($_POST['update']) {
mysql_query("....");
}
?>
Here is my code;
<?php
$box_query = mysql_query("SELECT * FROM `ta_boxs`");
while($box = mysql_fetch_array($box_query)) {
echo '<div class="box_content">';
echo '<div class="box">'."\n";
echo '<span class="box_top"></span>';
echo '<div class="box_header"><input type="text" id="title" name="title" class="title-input" value="'.$box['title'].'" /></div>';
echo '<span class="sept"></span>';
echo '<div class="admin-back">';
echo '<form id="form-'.$box['id'].'" name="form-'.$box['id'].'" method="post" action="">';
echo '<p class="sub"><span>Includes:</span> Search for these terms in Twitter Feeds.</p>';
echo '<p class="sub-small">Please enter one word per field or click "add word".</p>';
echo '<p><input type="text" id="search_term_1" name="search_term_1" value="'.$box['search_term_1'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_2" name="search_term_2" value="'.$box['search_term_2'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_3" name="search_term_3" value="'.$box['search_term_3'].'" class="term-input" />';
echo '<span class="hr"></span>';
echo '<p class="sub"><span>Excludes:</span> Ignore these terms in Twitter Feeds.</p>';
echo '<p class="sub-small">Please enter one word per field or click "add word".</p>';
echo '<p><input type="text" id="search_term_1" name="search_term_1" value="'.$box['exc_search_term_1'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_2" name="search_term_2" value="'.$box['exc_search_term_2'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_3" name="search_term_3" value="'.$box['exc_search_term_3'].'" class="term-input" />';
echo '<input type="hidden" id="update" name="update" value="yes" />'
echo '<p><input type="submit" id="update_'.$box['id'].'" name="update_'.$box['id'].'" value="Update" /></p>';
echo '</form>';
echo '</div>';
echo '</div>'."\n";
echo '<span class="box_bottom"></span>';
echo '</div>';
}
?>
There could be 1 output, or 100, but i need a way to save them all, onsubmit. Any ideas?
Since you're outputting each box in a different <form> you'll only every get one back.
If you change:
<input type="hidden" id="update" name="update" value="yes" />
to
<input type="hidden" id="update" name="update" value="' . $box['id'] . '" />
Then you'll be able to look which one was posted back.
I don't think your approach will work because you are generating multiple forms, so PHP will only get the one form that is submitted, and you won't be able to save all the changes on your page.
You might want to consider using one form and naming your inputs like an array (see http://php.net/manual/en/faq.html.php#faq.html.arrays) .
e.g. (simplified)
<form method="post">
<?php while($box = mysql_fetch_array($box_query)): ?>
<!-- div box thing -->
<input name="box[<?php echo $box['id'];?>][search_term_1]" value="<?php echo $box['search_term_1']; ?>">
<input name="box[<?php echo $box['id'];?>][search_term_2]" value="<?php echo $box['search_term_2']; ?>">
<input name="box[<?php echo $box['id'];?>][search_term_3]" value="<?php echo $box['search_term_3']; ?>">
<input name="box[<?php echo $box['id'];?>][exc_search_term_1]" value="<?php echo $box['exc_search_term_1']; ?>">
<input name="box[<?php echo $box['id'];?>][exc_search_term_2]" value="<?php echo $box['exc_search_term_2']; ?>">
<input name="box[<?php echo $box['id'];?>][exc_search_term_3]" value="<?php echo $box['exc_search_term_3']; ?>">
<!-- end div box thing -->
<?php endwhile; ?>
</form>
If you print_r($_POST) after submitting that form you should see that it will be fairly easy to loop over/process.
make one form ,
and in this form set all fields,
one button to submit ,
give to the input elements unique id to every row like you do to the form with the box id
Related
I'm trying to capture question ids and their answers. The problem
is that the value is "ON" when I print the array, it has the
question number correctly in the first cell but then the value in the
second cell is "ON". Here is my code:
function get_questions($quiz_id)
{
include'connection.php';
$stmt = $conn->prepare("select id,question,option1,option2,option3,option4,answer from questions where quiz_id=?");
$stmt->bind_param("i",$quiz_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($qid,$question,$option1,$option2,$option3,$option4,$answer);
$num_of_rows = $stmt->num_rows;
while($stmt->fetch()) {
echo $question;
echo "<br/>";
?>
<form method="POST"action="">
<input type="radio" name="radio[<?php echo $qid; ?>]" ]value="x"><?php echo $option1;?><br/>
<input type="radio" name="radio[<?php echo $qid; ?>]" ]value="y"><?php echo $option2;?><br/>
<input type="radio" name="radio[<?php echo $qid; ?>]" ]value="z"><?php echo $option3;?><br/>
<input type="radio" name="radio[<?php echo $qid; ?>]" ]value="f"><?php echo $option4;?><br/>
<!--<input type="radio" name="radio[<?php echo $qid; ?>]" ]value="<?php echo $option2;?>"><?php echo $option2;?><br/>
<input type="radio" name="radio[<?php echo $qid; ?>]" ]value="<?php echo $option3;?>"><?php echo $option3;?><br/>
<input type="radio" name="radio[<?php echo $qid; ?>]" ]value="<?php echo $option4;?>"><?php echo $option4;?><br/>
-->
<?php
}
?>
<input type="submit" name="submit" value="submit" >
</form>
<?php
if(isset($_POST['submit'])) {
$answers=$_POST['radio'];
print_r($answers);
// Iterate through each answer
}
}
Your problem is a simple syntax error:
]value="x">
This square bracket is changing the name of the attribute from value to ]value, so there is no value to be captured upon submission.
Also, make sure to move the opening form tag outside of your loop:
while($stmt->fetch()) {
...
<form method="POST"action=""> // <- this here opens a new tag with each iteration
because you close the tag outside the loop, meaning you're not creating valid html.
And while we're here, I'd suggest the alternative syntax when you have mixed php and html code:
<form method="POST" action="">
<?php while ($stmt->fetch()): ?>
<input type="radio"...
...
<?php endwhile ?>
<input type="submit" name="submit" value="submit" >
</form>
It makes it more readable and easier to follow than having to match curly braces.
I am trying to use PHP to update an SQL table using HTML forms.
I want the user to be able to search for a VCR name and display it details in a while loop and then an update form will appear for the user to change its details in the database.
However every time i press the update button on the update form, the variables that hold the new details empty and become undefined.
<?php require('connect.php'); ?>
<?php require('headerPrivate.php'); ?>
<?php require('session.php');?>
<?php
//SEARCH PHP CODE
//THIS WORKS FINE AND ALL THE DETAILS APPEAR
if(isset($_POST["search"]))
{
//CREATE VARIABLES
$username=$_SESSION['username'];
echo "username: ".$username;
echo '<br>';
$vcrName=$_POST['name'];
echo "VCR Name: ".$vcrName;
echo '<br>';
echo '<br>';
//SELECT * FROM PRODUCT
$sql="SELECT *
FROM product
INNER JOIN user
ON product.owner_ID=user.user_ID
WHERE username='$username' AND name='$vcrName'";
echo "SQL SELECT 1: ".$sql;
echo '<br>';
echo '<br>';
//$vcrName=$_POST['name'];
$result = mysqli_query($con,$sql);
echo '<div class="row">';
echo '<div class="col-xs-6 col-md-4">';
while ($row_all = mysqli_fetch_assoc($result))
{
echo '<form method="post">';
echo "<u>Title: ".$row_all["name"].'</u>';
echo '<br>';
echo '<small>';
echo " Price: ".$row_all["price"];
echo '</small>';
echo '<br>';
echo "<p><u>Short Description:</u> ".$row_all["short_descripton"]."</p>";
echo '<br>';
echo "<p><u>Long Description:</u> ".$row_all["long_description"]."</p>";
echo '<br>';
echo '<hr>';
echo '</form>';
echo '<div>';
}
echo '</div>';
}
?>
<content>
<!--SEARCH FOR VCR NAME-->
<form class="form" method="post">
<label for="name" class="sr-only">VCR Name</label>
<input type="text" name="name" class="form-control" placeholder="VCR Name" required="" autofocus="" autocomplete="off">
<button name="search" type="search" class="btn btn-success btn-block">Search</button>
</form>
<?php
//This is where i run into issues. The old name in the variable $vcrName is empty and i need it for the update SQL statement.
//UPDATE PHP
if(isset($_POST["alter"]))
{
//CREATE A SESSION VARIABLE FOR THE CUSTOMER ID
$customer_ID=$_SESSION['customer_ID'];
echo "Customer ID: ".$customer_ID;
echo '<br>';
//CREATE VARIABLES
$changeTitle=$_POST["titleChange"];
$changesDescChange=$_POST["sDescChange"];
$changelDescChange=$_POST["lDescChange"];
$changepriceChange=$_POST["priceChange"];
$vcrName=$_POST['name'];
//UPDATE SQL
$sql_update="UPDATE product
SET
name='$changeTitle',
short_descripton='$changesDescChange',
long_description='$changelDescChange',
price='$changepriceChange'
WHERE
owner_ID='$customer_ID' AND name='$vcrName'";
echo "SQL Update 0: ".$sql_update;
echo '<br>';
echo '<br>';
echo "Updated Name: ".$changeTitle;
echo '<br>';
echo '<br>';
echo "SQL Update 1: ".$sql_update;
return $sql_update;
echo '<br>';
echo '<br>';
$result_update = mysqli_query($con,$sql_update);
if($result_update){
echo "Update Successful!";
}
else {
echo "Update Unsuccessful";
}
}
?>
<!--UPDATE FORM-->
<form class="form" method="post">
<label for="titleChange" class="sr-only">VCR Name</label>
<input type="text" name="titleChange" class="form-control" placeholder="VCR Name" required="" autofocus="" autocomplete="off">
<label for="sDescChange" class="sr-only">Short Description</label>
<input type="text" name="sDescChange" class="form-control" placeholder="Short Description" required="" autofocus="" autocomplete="off">
<label for="lDescChange" class="sr-only">Long Description</label>
<input type="text" name="lDescChange" class="form-control" placeholder="Long Description" required="" autofocus="" autocomplete="off">
<label for="priceChange" class="sr-only">Price</label>
<input type="text" name="priceChange" class="form-control" placeholder="Price" required="" autofocus="" autocomplete="off">
<button name="alter" type="submit">Change</button>
</form>
</content>
</body>
</html>
Your PHP code refers to a POST variable that doesn't exist:
$vcrName=$_POST['name'];
In your update form, you need to pass it as a hidden value:
<input type="hidden" name="name" value="<?=htmlspecialchars($vcrName)?>"/>
It's not clear if these are two separate PHP scripts (or if so, why they are) so you may need to put in a database call to get that value. From a user interface point of view, one is typically given the existing values when updating a record anyway. This would mean getting the data and giving each form element a value attribute.
after i click on this a href, it ll pop out a form and i trying to pass a variable to the pop up form. This is in a while loop.
while($row = mysql_fetch_array($result))
{
$id=$row['file_id'];
echo '<span class=right>[edit]
}
This is the pop up form code
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("isiti");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET["id"]))
{
$id =$_GET["id"];
}
$result = mysql_query("SELECT * FROM publication where file_id='$id'");
$row1 = mysql_fetch_array($result);
$title=$row1['title'];
$author=$row1['author'];
$year=$row1['year'];
$abstract=$row1['abstract'];
if(!empty($_SESSION['username']))
{
echo'<div class="popup">';
echo'<form method="POST" action="public_edit.php" enctype="multipart/form-data">';
echo'<div>';
echo'<label for="citation">Title</label>';
echo'<input style="width:100%;" type="text" name="title" id="title" value="'.$title.'">';
echo'</div>';
echo'<div>';
echo'<label for="citation">Author</label>';
echo'<input style="width:100%;" type="text" name="author" id="author" value="'.$author.'">';
echo'</div>';
echo'<div>';
echo'<label for="citation">Year</label>';
echo'<input style="width:100%;" type="year" name="year" id="year" value="'.$year.'">';
echo'</div>';
echo'<div>';
echo'<label for="abstract">Abstract</label>';
echo'<textarea name="abstract" id="abstract" size="5000">'.$abstract.'</textarea>';
echo'</div>';
echo'<p>Rechoose your file here</p>';
echo'<input type="hidden" name="MAX_FILE_SIZE" value="2000000">';
echo'<input name="userfile" type="file" id="userfile"> ';
echo'<br/> ';
echo'<input name="submit" type="submit" value="Upload" style="width: 150px">';
echo'<a class="close" href="#close"></a>';
echo'</form>';
echo'</div>';
}
The problem i faced is that it do not pass the right id. no matter what link i click it show the data from the first id.
Thanks for helping me .
You need to pass the id as get parameter when calling that pop up. Replace with this the echo statement in first code
echo '<span class=right>[edit]';
$_GET works well for data sent by a query string. In this case, you are sending the data as the id of href tag.
so try attaching id to your query string.
echo '<span class=right>[edit]
What would be a reliable way to detect which form was submitted in a situation like below? All submit to the same page, which in turn does things based on which form was submitted. Many drawbacks have been pointed out to the way this is being done. To top it all, even querystrings go to the same script. How would you suggest this be done?
Form one has two input fields, form two has three.
<?php
if ( isset($_POST['valOne']) && isset($_POST['valTwo']) && isset($_POST['valThree']) ) {
echo 'This is form three';
} elseif ( isset($_POST['valOne']) && isset($_POST['valTwo']) ) {
echo 'This is form two';
} else {
echo 'Neither one or two';
}
$formOne = '<form method="post" action="http://localhost/dev/form.php">';
$formOne .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formOne .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formOne .= '<input type="hidden" name="secretVal" value="secretKey">';
$formOne .= '<input value="Add This" type="submit">';
$formOne .= '</form>';
$formTwo = '<form method="post" action="http://localhost/dev/form.php">';
$formTwo .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formTwo .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formTwo .= 'URL: <input type="text" name="valThree" value="Tar" autocomplete="off"><br>';
$formTwo .= '<input type="hidden" name="secretVal" value="secretKey">';
$formTwo .= '<input value="Add This" type="submit">';
$formTwo .= '</form>';
$formThree = '<a href="http://localhost/dev/form.php?do=getIt">This is GET. Get it?<a/>';
echo $formOne;
echo '<br>';
echo $formTwo;
echo '<br>';
echo $formThree;
?>
You could use a hidden input with different names for the 2 forms and on server side you can check with if(isset($_POST['hidden_for_form1'])) or if(isset($_POST['hidden_for_form2'])).
You could add a form_id parameter to the form action.
<form method='post' action='http://localhost/dev/form.php?form_id=1'>
Then in your code switch on $_GET["form_id"];
I'd use hidden inputs
<input type="hidden" name="form" value="form1">
Also on a side note, is there any reason you're storing the form code in a variable?
Add a hidden input:
<input type="hidden" name="form" value="one">
<?switch($_POST['form']){
case "one":
...
?>
You can also assign the name and value to a submit button, but that doesn't work if the user presses enter
You need to assign some name in submit, like:
<input type="submit" name="form1" value="Add This">
<input type="submit" name="form2" value="Add This">
<input type="submit" name="form3" value="Add This">
so..
if(isset($_POST['form1'])){ //do some stuff }
if(isset($_POST['form2'])){ //do some stuff }
if(isset($_POST['form3'])){ //do some stuff }
i have a problem here,so here's my code
<div id="educmaininfo">
<?php
foreach($cv->getEducation($_GET['cvid']) as $r){
echo "<a href='#' id='editeducation'>Edit</a> | ";
echo "<input type='hidden' name='cvid' value='".$r['ResumeID']."' />";
echo "<input type='hidden' name='educid' value='".$r['EducationID']."'/>";
echo "<a href='#' id='deleteeducation'>Delete</a><br />";
echo "Date From = ".$r['DateFrom']."<br />";
echo "Date To = ".$r['DateTo']."<br />";
echo "Title =".$r['Title']."<br />";
echo "Summary =".$r['Summary']."<br />";
echo "Place Organization =".$r['PlaceOrganization']."<br />";
echo "Emphasis of Study =".$r['EmphasisOfStudy']."<br />";
echo "Study Details =".$r['StudyDetails']."<br />";
echo "Qualifications =".$r['Qualifications']."<br /><br />";
}
?>
</div>
as you can see that code above, I added 2 hidden stuff, the cvid and the educid.
my question is, how to load this form below
<div id="educajaxinfo" style="display:none">
<table>
<form id="educdetails" method="post" action="">
<input type="hidden" name="cvid" id="cvid" value="<?php echo $v['ResumeID']; ?>" />
<tr><td>Date From:</td><td><input type="text" name="datefromeduc" id="datefromeduc" value="" /></td></tr>
<tr><td>Date To:</td><td><input type="text" name="datetoeduc" id="datetoeduc" value="" /></td></tr>
<tr><td>Title:</td><td><input type="text" name="titleeduc" id="titleeduc" value="" /></td></tr>
<tr><td>Summary:</td><td><textarea name="summaryeduc" id="summaryeduc" rows="10" cols="50"></textarea></td></tr>
<tr><td>Place Organization:</td><td><input type="text" name="pog" id="pog" value="" /></td></tr>
<tr><td>Emphasis of study:</td><td><input type="text" name="eos" id="eos" value=""></td></tr>
<tr><td>Study Details:</td><td><textarea name="studyeduc" id="studyeduc" rows="10" cols="50" ></textarea></td></tr>
<tr><td>Qualifications:</td><td><textarea name="qualificationseduc" id="qualificationseduc" rows="10" cols="50"></textarea></td></tr>
<tr><td><input type="submit" name="update" value="<?php if($count < 3){ echo 'Add';}else{ echo 'Update';}?>" /></td></tr>
</form>
</table>
</div>
with the existing data from the db table, that matches the cvid and educid ?
the flow goes like this, if user clicks the edit link, it should redirect him to the
form with the values loaded in the input forms...if in pure php i can do this by just
doing something like
e.g edit.php?cvid=cvid&educid=educid
how to do it in ajax way?
Use jQuery to call a PHP script that returns JSON encoded data. Then use the “success” callback function to inject the data into your form.
Use the jquery function like following
a href='#' onClick=test
(echo $cvid ,echo $educid ) id='editeducation'>Edit
function test(cvid,educid)
{
jQuery.post('edit.php?cvid=cvid&educid=educid',function(response){
jQuery('#educajaxinfo').html(response);
});
}
include the appropriate jquery min file to use above function.
on edit.php get the two id's and prepare a whole html then it will be shown in #educajaxinfo div