Display database values on option - php

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>

Related

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.

For loop inserts only 1 MySQL record

I have been working on a form that allows entering a menu item for a cafe establishment, alongside its ingredients (arrays of data). Unfortunately, a problem came up as it only executes 1 query even though 2 or more ingredients were entered in the form (dynamic, jQuery).
Here is the PHP code:
<?php
include("session.php");
if (isset($_POST['submit'])) {
$productname = $_POST['product_name'];
$categoryID = $_POST['categoryID'];
$price = $_POST['srp'];
// ingredients
$ingredients = $_POST['ingredients'];
$qty = $_POST['qty'];
$measure = $_POST['measure'];
if (!empty($productname) && !empty($categoryID) && !empty($price) && !empty($ingredients) && !empty($qty) && !empty($measure)) {
for ($i=0; $i < count($ingredients); $i++) {
if ($ingredients[$i] != "" && $qty[$i] != "" && $measure[$i] != "") {
mysqli_query($db, "insert into individual_ingredients values ('', '$productname', '{$ingredients[$i]}', '{$qty[$i]}', '{$measure[$i]}')");
}
}
mysqli_query($db, "insert into end_products values ('', '$productname', '$price', '', '$categoryID')");
mysqli_query($db, "insert into audit_trail values ('', now(), '{$_SESSION['login_user']}', 'New end product added')");
header("location: end_products.php");
} else {
echo '<font color="red">'."Incomplete data entered".'</font>';
}
}
?>
And here is the HTML form and JQuery:
<html>
<head>
<title><?php echo $login_session; ?> | New End Product Record</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Bootstrap js library -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//add more fields group
$(".addMore").click(function(){
var fieldHTML = '<div class="form-group fieldGroup">'+$(".fieldGroupCopy").html()+'</div>';
$('body').find('.fieldGroup:last').after(fieldHTML);
});
//remove fields group
$("body").on("click",".remove",function(){
$(this).parents(".fieldGroup").remove();
});
});
</script>
</head>
<body>
HTML form:
<table style="margin: 5% -1% 0 -10%; font-size: 0.9em">
<tr>
<form action="new_end_product_record.php" method="post">
<td>Name</td>
<td><input type="text" name="product_name"></td>
<td>Raw Material/s Used</td>
<td>
<div class="fieldGroup">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
ADD
<br /><br />
</div>
<!-- second set -->
<div class="fieldGroupCopy" style="display: none;">
<div class="input-group">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
REMOVE
<br /><br />
</div>
</div>
</td>
</tr>
<tr>
<td>SRP</td>
<td><input type="text" name="srp"></td>
</tr>
<tr>
<td>Category</td>
<td>
<select name="categoryID">
<option value="">Select category...</option>
<!--list all categories in the database-->
<?php
$cat_query = "select category_ID, name from end_products_categories";
$get_cats = mysqli_query($db, $cat_query);
while ($option = mysqli_fetch_assoc($get_cats)) { ?>
<option value="<?php echo $option['category_ID']; ?>"><?php echo $option['name']?></option>
<?php } ?>
</select>
</td>
<!-- <td>Expiration</td>
<td><input type="date"></input></td> -->
</tr>
</table><br>
<input type="submit" class="button" name="submit" value="ADD RECORD">
<input type="reset" value="ERASE ALL">
</div></form>
</div>
</body>
</html>
Is there a problem with the loop or with the HTML form that prevents the second to the last set of values from being inserted? Any help would be appreciated.

Cant fetch variable after submitting the form

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.

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>

Updating Post not working

I recently made a code that updates my posts on my blog. It worked perfectly on localhost. But when i uploaded it online it did not work any more. The weird thing is it doesn't even display a error so i have no idea where to look. Can someone please help me ?
require('config.php');
$query = "SELECT * FROM project ORDER BY idproject DESC";
$result = mysqli_query($verbinding, $query ) or die (mysqli_error('kan geen verbinding maken met de database'));
if(isset($_POST['editBut'])){
$editTitle = $_POST['editName'];
$editThis = mysqli_query($verbinding, "SELECT * FROM project WHERE title = '".$editTitle."'");
$values = mysqli_fetch_assoc($editThis);
}
if(isset($_POST['update'])){
$editedTitle = $_POST['newTitle'];
$editedText = $_POST['newTekst'];
$oldTitle = $_POST['oldTitle'];
$date = $_POST['datum'];
$updater = mysqli_query($verbinding, "UPDATE Project SET title='".$editedTitle."', content='".$editedText."' WHERE title='".$oldTitle."' AND datum='".$date."'");
echo $updater;
header('location:editPost.php?id=1');
}
if(isset($_GET['id'])){
echo 'post has been succesfully updated';
}
<?php if(isset($_POST['editBut'])){ ?>
<form action="" method="post">
Title: <input type="text" name="newTitle" value="<?php echo $values['title'] ?>"><br>
Text: <textarea type="text" name="newTekst" id="newTekst"><?php echo $values['content'] ?></textarea><br>
<input type="hidden" value="<?php echo $values['title'] ?>" name="oldTitle">
<input type="hidden" value="<?php echo $values['datum'] ?>" name="datum">
<input type="submit" name="update" value="Edit post">
</form>
<?php } else { ?>
<p>Find the post you want to edit:</p>
<form action="" method="post">
<select name="editName">
<?php
while ($row = mysqli_fetch_assoc($result)) {
?> <option value="<?php echo $row['title'] ?>"><?php echo $row['title'] ?></option>
<?php } ?>
</select>
<input type="submit" name="editBut" value="Choose">
</form>
<?php } ?>
In update query replace your table name with small letter.
replace Project with project

Categories