Cant fetch variable after submitting the form - php

The variable $role_id1 is not being fetched in $role_id in $_POST['add sub menu'].
I want to store $role_id1 in $role_id and insert into database.Afer i click the submit button the role_id1 is fetching the parent menu but after i click add sub menu the role_id is storing 0 at backend.But i want it to store the vale of role_id1 which is being fetched after i click submit.Suggest any solution if possible.
<?php
$dbcon = new MySQLi("localhost","root","","menu");
if(isset($_POST['add_main_menu']))
{
$menu_name = $_POST['menu_name'];
$parent_id = 0;
$role_id = $_POST['role_id'];
$menu_link = $_POST['mn_link'];
$sql=$dbcon->query("INSERT INTO menu VALUES('','$menu_name','$parent_id','$role_id','$menu_link')");
}
if(isset($_POST['add_sub_menu']))
{
$parent_id = $_POST['parent'];
$name = $_POST['sub_menu_name'];
$role_id = $role_id1;
$menu_link = $_POST['sub_menu_link'];
$sql=$dbcon->query("INSERT INTO menu VALUES('','$name','$parent_id','$role_id','$menu_link')");
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Dropdown Menu</title>
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
</head>
<body>
<div id="head">
<div class="wrap"><br />
<h1>Back to menu</h1>
</div>
</div>
<center>
<pre>
<form method="post">
<input type="text" placeholder="menu name :" name="menu name" /><br />
<input type="text" placeholder="role id :" name="role_id" /><br />
<input type="text" placeholder="menu link :" name="mn_link" /><br />
<button type="submit" name="add_main_menu">Add main menu</button>
</form>
</pre>
<br />
<pre>
<form method="post">
<select name="role_id">
<option selected="selected">select role id</option>
<?php
$res=$dbcon->query("SELECT distinct role_id FROM menu");
while($row=$res->fetch_array())
{
?>
<option value="<?php echo $row['role_id']; ?>"><?php echo $row['role_id']; ?></option>
<?php
}
?>
</select><br />
<input type="submit" value="submit" name="submit">
<?php if(isset($_POST['submit']))
{
?>
<select name="parent">
<option selected="selected">select parent menu</option>
<?php
$role_id1 = $_POST['role_id'];
$res=$dbcon->query("SELECT * FROM menu where role_id= $role_id1 AND parent_id=0 ");
while($row=$res->fetch_array())
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']
;
?></option>
<?php
}
}
?>
</select><br />
<input type="text" placeholder="menu name :" name="sub_menu_name" /><br />
<input type="text" placeholder="menu link :" name="sub_menu_link" /><br />
<button type="submit" name="add_sub_menu">Add sub menu</button>
</form>
</pre>
back to main page
</center>
</body>
</html>

$role_id1 = $_POST['role_id'];
The lifetime of $role_id1 is where your scripts stops (last line) and output is sent to the browser (you see the form again).
So on the line in the top of your code:
$role_id = $role_id1;
$role_id1 doesn't exists anymore. If you view your error-log (or turn on display_errors), you would see a Notice: Undefined variable: role_id1 in ...
If you want to keep that value, put it in a hidden element so that it will be included in the POST-data the next time you submit that form:
echo '<input type="hidden" name="previous_role_id" value="' . htmlspecialchars($_POST['role_id']) . '">';
One sidenote (for completeness), although the element is hidden the value can be altered by the user.

Related

How to update the database if I change the dropdown list element and checkbox value

I have created one form in that I have put one drop down list and group of checkbox.
If user select any item from that drop down list than particular item should updated in database(Ex.first user has select division A from drop down list than the A should enter into database and if after some time same user change division from A to B than in database in place of A data should B when user press update button.
In the group of checkbox if user change (select or deselect) checkbox compare to previous input than respective checkbox value should updated in database.(Ex. If user has checked two checkbox than the particular checkbox value should update in database and after some time same user has checked all three checkbox or only one checkbox and particular change should update in database when user click on update button
Here I have put my code. If anyone know solution than please help.
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db_new", $connection);
$query=mysql_query("SELECT * FROM student_info where id=17");
$row= mysql_fetch_row($query);
$rollno = $row[1];
$name = $row[2];
$division= $row[3];
$std = $row[4];
$gender = $row[5];
$subject=mysql_query("select * from student_info where id=17");
while($fetch=mysql_fetch_object($subject))
{
$r=$fetch->subject;
$sub=explode(",",$r);
}
if(count($_GET)>0){
$rollno=$_GET['rollno'];
$name=$_GET['name'];
$std=$_GET['std'];
$gender=$_GET['gender'];
$update=mysql_query("update student_info set roll_no='$rollno', name='$name',
std='$std', gender='$gender' where id='17'",$connection);
}
mysql_close($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Form</title>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="jquery%20validate/jquery.validate.min.js"></script>
<script src="jquery%20validate/additional-methods.min.js"></script>
<script src="form.js"></script>
</head>
<body>
<form id="editform" method="GET" action="task.php">
<div>
<h1>Form</h1>
<label><b>Roll No:</b></label>
<input id="rollno" name="rollno" type="text" value="<?php echo $rollno ?>"> <br><br>
<label><b>Name:</b></label>
<input id="name" name="name" type="text" value="<?php echo $name ?>"> <br><br>
<label><b>Division:</b></label>
<select id="division">
<option value=" " <?php if (!empty($division) && $division == ' ') echo 'selected = "selected"'; ?>>--select--</option>
<option value="A" <?php if (!empty($division) && $division == 'A') echo 'selected = "selected"'; ?>>A</option>
<option value="B" <?php if (!empty($division) && $division == 'B') echo 'selected = "selected"'; ?>>B</option>
<option value="C" <?php if (!empty($division) && $division == 'C') echo 'selected = "selected"'; ?>>C</option>
<option value="D" <?php if (!empty($division) && $division == 'D') echo 'selected = "selected"'; ?>>D</option>
</select><br><br>
<label><b>Std:</b></label>
<input id="std" name="std" type="text" value="<?php echo $std ?>"><br><br>
<label><b>Gender:</b></label>
<input type="radio" name="gender" value="male" <?php if($gender=='male'){ echo "checked=checked";}?>>Male
<input type="radio" name="gender" value="female" <?php if($gender=='female'){ echo "checked=checked";}?>>Female<br><br>
<label><b>Subject:</b></label><br>
<input type="checkbox" name="box[]" class="subject" value="maths" <?php if (in_array("maths", $sub)){echo "checked";}?>>maths<br>
<input type="checkbox" name="box[]" class="subject" value="science" <?php if (in_array("science", $sub)){echo "checked";}?>>science<br>
<input type="checkbox" name="box[]" class="subject" value="english" <?php if (in_array("english", $sub)){echo "checked";}?>>english<br>
<input id="submit" type="submit" value="submit">
<input id="update" type="submit" value="update">
</div>
</form>
</body>
</html>
You can use jquery ajax to update the data on select and on change of dropdown.
$.post('page.php',{parameter:value},function(data){
//operation performed after insertion
});

How to make PHP drop down menu be taken as a HTML form input

So I've made a drop down menu (using PHP), and I'm not sure how to make it so that it can be taken as an input into a HTML form?
This is the PHP code:
<?php
$dropdownsql = "SELECT prodName FROM tblProduct";
$dropdownresult = #mysqli_query($connect, $dropdownsql);
echo "<select name='prodID'>";
while ($row = mysqli_fetch_array($dropdownresult, MYSQLI_ASSOC)) {
echo "<option value='" . $row['prodID'] . "'>" . $row['prodName'] . "</option>";
}
echo "</select>";
?>
And this is the HTML form code:
<form action="addOrder.php" method="post">
<p>
Order Date*:
<input type="text" name="orderDate" maxlength='70' required>
<p>
Order Location*:
<input type="text" name="orderLocation" maxlength='255' required>
<p>
Order Product*:
<p>
Order System*:
<input type="text" name="orderSystem" required>
<p>
<input type="submit" name="submit" value="Add Order">* Means that the field is required.
<input type="hidden" name="submitted" value="TRUE">
</form>
*Note that I want the input for Order Product
I have rewritten this to make it secure. Check if it works for you:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Link Games</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
include 'header.php';
include 'menu.php';
try {
$connect = new PDO("mysql:dbhost=localhost;dbname=linkgamesDB", 'username', 'password');
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
<div id="content">
<p class="headers"><strong>Add Order</strong></p>
<?php
#Check that the form is submitted
if (isset($_POST['submitted'])) {
#Create then run the query
$query= $connect->prepare("INSERT INTO tblOrder(orderDate, orderLocation, orderProd, orderSystem) VALUES (?, ?, ?, ?)")
$query->bindValue(1, $_POST['orderDate']);
$query->bindValue(2, $_POST['orderLocation']);
$query->bindValue(3, $_POST['orderProd']);
$query->bindValue(4, $_POST['orderSystem']);
$query->execute();
#Check if there is an error in query and display relevant message
if ($query->rowCount() > 0) {
echo '<p class="records">Thank you! Record Added.</p>';
} else {
echo '<p class="records">Error. No record added.</p>';
}
}
?>
<form action="addOrder.php" method="post"><p>
Order Date*: <input type="text" name="orderDate" maxlength='70' required><p>
Order Location*: <input type="text" name="orderLocation" maxlength='255'required><p>
Order Product*: <select name='orderProd'>
<?php
$dropdownsql = $connect->prepare("SELECT prodID, prodName FROM tblProduct");
$dropdownsql->execute();
$r = $dropdownsql->fetchAll();
foreach($r AS $row):
?>
<option value="<?php echo $row['prodID'];?>"><?php echo $row['prodName'];?></option>
<?php endforeach;?>
</select>
<p>
Order System*: <input type="text" name="orderSystem" required><p>
<input type="submit" name="submit" value="Add Order"> * Means that the field is required.
<input type="hidden" name="submitted" value="TRUE">
</form>
</div>
</body>
</html>

Display database values on option

I am trying to display the saved data in the database on select before a user can update other choice. I am not really sure how to code it. Can anyone come out with possible solution? Had tried many ways but unable to do so.
Update: I have found out the problem why the options does not show.
This is my code:
`
$consentId = $_GET['consent_id'];
$retrieveConsent = "SELECT * FROM consent, leavetype WHERE consent.type_of_leave = leavetype.type_of_leave";
$retrieveResult = mysqli_query($link, $retrieveConsent) or die("Retrieve Error" . mysqli_error($link));
$queryleavetype = "SELECT * FROM leavetype";
$queryleaveresult = mysqli_query($link, $queryleavetype) or die("Leave Retrieve Error " . mysqli_error($link));
$row = mysqli_fetch_array($retrieveResult);
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Consent </title>
</head>
<body>
<div class="ui-content">
<h3><b>Edit Leave</b></h3>
<form action="doEditConsent.php" method="post" data-ajax="false">
<input type="hidden" name="cId" value="<?php echo $row['consent_id']; ?>"/>
<label for="dateFrom" ><b>Date From:</b></label>
<input type="date" id="dateFrom" name="newDateFrom" value="<?php echo $row['consent_date_from']; ?>" required>
<br>
<label for="dateTo" ><b>Date To:</b></label>
<input type="date" id="dateTo" name="newDateTo" value="<?php echo $row['consent_date_to']; ?>" required>
<br>
<label for="reason" ><b>Leave Type:</b></label>
<select name="leaveType" id="leaveType" data-mini="true">
<?php
while ($rowleave = mysqli_fetch_array($queryleaveresult)) {
?>
<option value="<?php echo $rowleave['type_of_leave']; ?>">
<?php echo $rowleave['leave_type']; ?>
</option>
<?php
};
?>
</select>
<br>
<button class="ui-btn ui-corner-all" type="submit" >Submit</button>
</form>
</div>
<?php
}
}
?>
</body>
</html>`
Try this, hopefully it will help you:
<select name="leaveType" id="leaveType" data-mini="true">
<option value=""></option>
<?php
$previous_selected_value = 'previous_selected_value';//get the previous value and assign it to this variable
while ($rowleave = mysqli_fetch_array($queryleaveresult)) {
$selected = ($rowleave['type_of_leave'] == $previous_selected_value) ? " selected='selected'" : "";
echo '<option value="'.$rowleave['type_of_leave'].'"'.$selected.'>'.$rowleave['leave_type'].'</option>';
}
?>
</select>

show data in multiple textbox in php

I want to show all the names of my tb_app which is currently have (4)names stored and show it on my textboxes...can anyone help me make my code work? I'm just a beginner at programming.
current code:
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$sql = "SELECT name FROM tb_app";
while($rows = mysql_fetch_array($sql)){
$name = $rows['name'];
}
?>
Name List: <br />
<input type="text" value="<?php echo $name[0] ?>" /> <br />
<input type="text" value="<?php echo $name[1] ?>" /> <br />
<input type="text" value="<?php echo $name[2] ?>" /> <br />
<input type="text" value="<?php echo $name[3] ?>" /> <br />
</body>
</html>
Right now you are overwriting the $name variable in each iteration of your loop. You want to treat $name as an array instead, and add an element to the array in each iteration.
Change this:
$name = $rows['name'];
To this:
$name[] = $rows['name'];
You could of course echo your textbox directly inside your while loop as well, and skip the $name variable. However it's good practice to separate your DB or business logic from your display logic, which you are (somewhat) doing. In fact I'd recommend moving your PHP code to the very top of the page, before your opening <html> tag even, and limit how much PHP you mix in with your html.
A more dynamic way (i.e you have less or more then 4 names):
<html>
<head>
<title>test</title>
</head>
<body>
Name List: <br />
<?php
include('include/connect.php');
$sql = "SELECT name FROM tb_app";
while($rows = mysql_fetch_array($sql)){
echo '<input type="text" value="'. $rows['name'] .'" /> <br />';
}
?>
</body>
</html>
You could go even further:
Change name to names:
while($rows = mysql_fetch_array($sql)){
$names[] = $rows['name'];
}
And then
Name List:
<?php foreach ($names as $name): ?>
<input type="text" value="<?php echo $name ?>" /> <br />
<?php endforeach; ?>

In PHP how to output the contents of a radiobox array using POST?

I want to output the values of the checkbox in the same way I'm outputting the values from the text fields. Since the checkbox can have multiple inputs I'm using an array for that but trying to cycle through the array for values hasn't worked for me.
tried foreach($type as $item) and echoing $item within the HTML like it says in the PHP book I have but that hasn't worked.
How should I do and where should the code be? I'm also unable to use PHP within the HTML for some reason, I'm not sure why that is or if its something to do with the echo<<<_END or not. Help appreciated.
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre'];
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = $_POST['type'];
else $type = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: $game in the $genre genre and of the type<br />
<form method="post" action="formtest.php">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
_END;
?>
With the form as it is now, $_POST['type'] will be an array since it's using checkboxes (and named appropriately), not radios. Here I just implode it for display, but you can loop through it like any array. It should be worth noting that any time you're wondering what a form is giving you, you can var_dump($_POST) or var_dump($_GET) depending on where the data is coming from. It helps a lot with debugging.
Here's what I got, I switched from heredoc, but your heredoc should work fine if you add $type back in somewhere, I didn't notice it in the original code:
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre']; //Edit: Fixed line, oops
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = implode(', ',$_POST['type']);
else $type = "(Not entered)";
//Normally I'd specify a charset, but for simplicity's sake I won't here.
$type = htmlspecialchars($type);
$game = htmlspecialchars($game);
$genre = htmlspecialchars($genre);
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in
the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
Addendum:
If you switched and used radios like
<input type="radio" name="type" value="Downloadable" />
$_POST['type'] would be a simple string since you can only select one of the set.
To the file you post it the type[] will be saved as an array. For example
$a=$_POST['type'];
Although I don't find any point in doing this to radio-buttons, because their purpose is to pass only 1 value(unless you want specifically to).
Ok, first you don't need to echo the entire html output. Second your questions says radio buttons, but the html shows checkboxes. A radio field will only produce one result so you don't need [] after then name. Checkboxes will return an array when named with a []. So if you are using checkboxes you will need to process the result as an array. If you change the field to radio it should work fine.
<?php // formtest.php
if (isset($_POST['game'])) {
$game = $_POST['game'];
}
else { $game = "(Not entered)"; }
if (isset($_POST['genre'])) {
$genre = $_POST['genre'];
}
else { $genre = "(Not entered)"; }
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else { $type = "(Not entered)"; }
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="test.php">
What is your game?
<input type="text" name="game" <?php if ($game != "(Not entered)") { echo "value='" . $game . "'"; } ?> />
<br />
What is your genre?
<input type="text" name="genre" <?php if ($genre != "(Not entered)") { echo "value='" . $genre . "'"; } ?> />
<br />
Type?
Retail <input type="radio" name="type" value="Retail" <?php if ($type == "Retail") { echo "checked"; } ?> />
Downloadable <input type="radio" name="type" value="Downloadable" <?php if ($type == "Downloadable") { echo "checked"; } ?> />
Free <input type="radio" name="type" value="Free" <?php if ($type == "Free") { echo "checked"; } ?> />
<br />
<input type="submit" />
</form>
</body>
</html>

Categories