passing two values (one from text, one hidden) using html and php - php

I really struggle here and I spent much time on a solution but it seems that I missing something here.
So I have one page that I have 2 values:
$semesterID = $_GET['semesterID'];
$semesterID_old = $semesterID;
I do this as I want to pass 2 values on my next page. I am trying to do that with this:
<form action=ed_semester_v2.php method="post">
<div id="name">
<h2 class="name">Semester ID</h2>
<input class="subjectname" type="text" name="sem_id" id="sem_id" value= "<?php echo $semesterID; ?> " /> <br>
</div>
<input type="hidden" name="semesterID_old" value= "<?php $semesterID_old; ?>"/>
<button type="submit" value="Submit" name="submit">SAVE CHANGES</button>
</form>
The one $semesterID pass fine to the next page but the semesterID_old no. Just to clarify that the semesterid might change by the user and that's ok.
In my next page, I use this code:
if(isset($_POST['submit'])) {
$first_name=$_POST['sem_id'];
$last_name=$_POST['sem_name'];
$semesterID_old= $_POST['semesterID_old'];
if (empty($last_name)) {
echo "Name is empty";
} else {
$query = "UPDATE semesters SET name = '$last_name' where semesterid='$first_name'";
}
if (!mysqli_query($dbconnect, $query)) {
die('An error occurred when submitting your review.');
} else {
// echo "Thanks for your review.";
}
}
echo $first_name;
echo $semesterID_old;
First_name is fine but semesterID_old says that's undefined.
Any help would be much appreciated.

Just change echo semesterID_old; to echo $semesterID_old;

Related

PDO MySQL Update not working correctly on edit page

A 'quiz' currently contains a quiz id, name, description and topic (from a topic table).
I am wanting to setup a simple 'Edit Quiz' page.
The problem is - if a quiz is called 'Quiz1' and I change the quiz name on the edit page to 'Quiz2', once the save button is clicked it will revert back to 'Quiz1' and not stored.
I have setup an echo as shown in the code to check that they are actually getting stored, after the save button is clicked it would show 'Quiz1' but this value is not stored in my database. The SQL Has been tested on PhpMyAdmin and seems to work too.
PHP Code:
<? if (!empty($_POST)) {
$id = $_POST['qzid'];
$qzname = $_POST['qzname'];
$qzdesc = $_POST['qzdesc'];
$ctname = $_POST['ctname'];
$checkQuiz = $db->prepare("SELECT qz_name FROM quizzes WHERE qz_name = :qz_name");
$checkQuiz->execute(array(':qz_name' => $qzname));
$qzChanged = "Quiz details updated successfully";
$sql = "UPDATE quizzes SET `qz_name` = :qzname, `qz_desc` = :qzdesc WHERE `quizzes`.`id` = :qzid";
$q = $db->prepare($sql);
$q->execute(array(':qzname' => $qzname, ':qzdesc' => $qzdesc, ':qzid' => $id));
echo $qzname, $qzdesc; //THIS RETURNS THE CHANGED VALUES
}?>
HTML Code:
<form action="edit_quiz.php?id=<?php echo $row['id'] ?>" method="POST">
<input type="hidden" name="qzid" id="qzid" value=""/>
<!-- selection box -->
<p>Topic Name:
<select class="form-control" name="ctname" id="ctname">
<?php
while ($tresult = $stmt->fetch()) {
echo "<option>" . $tresult["ct_name"] . "</option>";
}
?>
</select>
</p>
<p>Quiz Name: <input type="text" name="qzname" value="<?php echo $row['qz_name']; ?>"/></p>
<p>Quiz Description: <textarea name="qzdesc" value=""/><?php echo $row['qz_desc']; ?> </textarea></p>
<input type="submit" class="btn btn-success" value="Save"/> <a class="btn" href="quizzes.php">Back</a>
Please note this code has been simplified.
Any help I would appreciate very much thanks!
You are not posting the id it looks like.
Is your database named localhost, otherwise remove that part.

Trying PHP IF Else Statements for the first time

I'm learning PHP and trying to understand the if .. else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age.
Here is my code so far:
My html file:
<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>
My php file:
<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25){
echo "$yes";
}else{
echo "$no";
}
?>
You catch the user input inside the $_POST superglobal var (because the method of your form is POST.
So
<?php
$age = 25;
should be
<?php
$age = $_POST['age'];
There is an error in HTML too. This
<input type="submit" name="age" value="Submit"/>
should be
<input type="text" name="age" value=""/>
<input type="submit" value="Click to submit"/>
Because you want one input and one button. So one html element for each element.
and <input></input> must be cleared because it's not valid syntax :-)
<form action="questions.php" method="post">
<p>How old is Kenny?</p><input type="text" name="age"></input>
<input type="submit" value="Submit"/>
</form>
$age = (int) $_POST["age"];
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25) {
echo $yes;
} else {
echo $no;
}
<?php
/* Test that the request is made via POST and that the age has been submitted too */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['age'] ) ){
/*
ensure the age is an integer rather than a string ..
though for this not overly important
*/
$age=intval( $_POST['age'] );
if( $age==25 ) echo "Congratulations";
else echo "Bad luck!";
}
?>
<form action="questions.php" method="post">
<p>How old is Kenny?
<input type='text' name='age' placeholder='eg: 16' />
<input type="submit" value="Submit" />
</p>
</form>
A simple html form, note that the submit button does not carry the values you want to process, they are supplied via the input text element.
First of all, you need to echo the variable; echoing "$no" will keep it as a string. Remove the quotes from "$no" and "$yes" in your if then statement. Otherwise, your code seems sound!

$_POST not working

I am trying to run the below query which basically create a submit button. However when I am trying to click the Accept Request button it is not resolving the if condition and directly echo what is written in else condition.
Can someone help why this would be happening?
<?php
if(isset($_POST['acceptrequest'.$user_from]))
{
echo "you are now freind !";
} else
{
echo 'Error in reading - acceptrequest'.$user_from;
}
?>
<form action = "friend_request.php" method = "POST">
<input type="submit" name = "acceptrequest<?php echo $user_from;?>"
value="Accept Request" style = "margin-left: 5px;" />
<input type="submit" name = "ignorerequest<?php echo $user_from;?>"
value="Ignore Request" style = "margin-left: 5px;" />
</form>
In general, you ought not use variables to define the name of a form input.
Specifically because of the "variable" nature of variables, you can't be sure that the name posted will match the name you're looking for.
In order to keep your application stateless, you should instead post the variable kn its own hidden input.
Below, I modified your form to post user_from as its own input, separate from acceptrequest and ignorerequest.
This should fix any state issues that you were experiencing before.
<?php
if (isset($_POST['acceptrequest')) {
echo "You are now friend with {$_POST['user_from']}!";
} else if (isset($_POST['ignorerequest')) {
echo "You ignored the request from {$_POST['user_from']}!";
} else {
echo 'Error in reading - acceptrequest'.$user_from;
}
?>
<form action = "friend_request.php" method="POST">
<input type="hidden" name="user_from"
value="<?php echo $user_from;?>" />
<input type="submit" name="acceptrequest"
value="Accept Request" style = "margin-left: 5px;" />
<input type="submit" name="ignorerequest"
value="Ignore Request" style = "margin-left: 5px;" />
</form>
Maybe You haven't set all variables. Try to define that and use: $
So create something like: $acceptrequest == something

Php Repeatable region

So i got this code, at the moment it is repeating everything , and i just wanted it to repeat the echo, so i get all usernames from it, if i leave it as it is it will also repeat the form when i press a username. Every time i tried to ajust it, it just gave me syntax errors
<?php do { ?>
<?php
$username = $row_mensagens['username'];
$user = $row_mensagens['id'];
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form>
Introduz mensagem : <br>
<textarea name='message' rows='7' cols='60'></textarea>
<br><br>
<input type='submit' value="Send Message" />
</form>
<?php
} else {
echo "<p><a href='mensagens.php?user=$user'>$username</a></p>";
}
?>
<?php } while ($row_mensagens = mysql_fetch_assoc($mensagens)); ?>
that do { } while() will always repeat as many as the number of records come from database.
You can do it this way:
<?php
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form>
<input type="hidden" name="user" value="<?php echo $_GET['user']; ?>" /> <!-- hidden field so you can process to who -->
Introduz mensagem : <br>
<textarea name='message' rows='7' cols='60'></textarea>
<br>
<br>
<input type='submit' value="Send Message" />
</form>
<?php
} else {
do {
$username = $row_mensagens['username'];
$user = $row_mensagens['id'];
echo "<p><a href='mensagens.php?user=$user'>$username</a></p>";
} while ($row_mensagens = mysql_fetch_assoc($mensagens));
}
?>
Move do { inside else and show the form only if you have a $_GET['user']
I have also added for you a hidden field, so you know who to send message.
Hope you understand how this works. Documentation on Control Structures: do-while
I also suggest to make that form a post form, as by default it is a get form, and since you have a textarea you are more likely to bump into errors if the message is too long.
LE: Another suggestion, try to move to PDO or mysqli_* functions since mysql_* functions are considered deprecated as of PHP 5.5 and have some good chances to be removed.

Post form values where Field Names are dynamically created from a loop?

I have a page that is created dynamically from the information that a user has submitted on a previous page. For example on page 1, the user inputs some department names. They can enter as many as they want. On page 2, multiple sections are created for each department that was entered on page one. Inside each of these sections are going to be forms, I currently have it set up so that the names of the forms are created using a variable $a. I need to know how to post these items once the submit button in each section is clicked. I have tried several different ways and nothing is working. I want it so that ONLY the items with the same $a value as the submit button's $a get posted.
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a;?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a;?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
<?php
echo "</div>";
}
?>
*EDIT I need everything to be in one form because the point of the page is to add up all of the values that will be inserted into each of the individual sections later. *
**EDIT 2 :
I figured it out using #dirt 's jquery suggestion.
HTML:
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
<div id=$a>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a ?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a ?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<button type="submit" name="areaSub" value="<?php echo $a ?>" />Add</button>
<?php
echo "</div></div>";
} ?>
jQuery:
<script>
$(document).ready(function() {
$('#<?php echo $a ?>').submit(function() {
.post("include/action.php")
});
});
</script>
PHP:
if(isset($_POST['areaSub'])) {
$areaval = intval($_POST['areaSub']);
$area = mysql_real_escape_string($_POST["dep_area".$areaval.""]);
list($area_id, $area_name) = explode(',', $area, 2);
$bdep = mysql_real_escape_string($_POST["bdep".$areaval.""]);
echo $areaval;
echo $area_name;
echo $bdep;
}
EDIT: If its a single form with multiple sections and you don't want to trim out unwanted form data after the POST then I think you must use jQuery to trim the form values prior to the post to the server, so see my jQuery portion below for a crued example of how you would go about only posting the data for the selected button.
Short answer would be to use the Name/Value attributes of the submit button and evaluate that once posted. Multiple buttons with the same name can have different values and the values don't have to be the labels.
Example:
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<?php
# _POST:
if (isset($_POST['submit']) && $_POST['submit'] == '1') {
echo 'Department 1';
}
if (isset($_POST['submit']) && $_POST['submit'] == '2') {
echo 'Department 2';
}
?>
You could also use jQuery to get all elements contained in a certain Div ID. Something like (this is rough idea):
<div id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
</div>
jQuery:
$('#<?php echo $a; ?>').submit(function() {
do_something_with_form_$a
});
I'm not sure if I understand completely... but the issue you're having is that, when a user hits the 'submit' button for a given set of values (a given department), it submits ALL of the data on the page? And you only want the input fields for that specific area submitted?
Section off forms with the tag:
<form> </form>
So, you'll have multiple areas:
while(...) {
<form method="..." name="form $a">
<input name="... $a">
<input name="... $a">
...
<submit>
</form>
}
(Obviously this is pseudocode, adjust accordingly)

Categories