I used to be program in .Net so PHP with MySQL is very new for me.
I wanted to have same form for displaying and updating the DB, with work fine. I dont have issues with that, but after the save happens, the text inputs retains old value.
My HTML side
<select class="form-control" name="form1">
<option selected="selected">
<?php echo htmlspecialchars($GLO_variable1); ?>
</option>
<option value="option1">option 1</option>
<option value="option2">option 2</option>
</select>
<input class="btn btn-primary" type="submit" name="updaterecord" value="Update Summary">
I wanted the options to to reflect current record on the DB, which works fine when viewing/getting the record from DB.
<?php
function GetRecord(){
require 'conn.php';
if(!session_id()) session_start();
$globalinc = $_SESSION["globalinc"];
if(isset($globalinc)){
$sqlget="SELECT * FROM t_summary WHERE SNOW_INC= '". $globalinc ."'";
$result = mysqli_query($conn, $sqlget);
$getrecordarray = mysqli_fetch_assoc($result);
$GLOBALS['GLO_PRIORITY'] = $getrecordarray['PRIORITY'];
$GLOBALS['GLO_INC_STATEMENT'] = $getrecordarray['INC_STATEMENT'];
mysqli_free_result($result);
mysqli_close($conn);
}
}
?>
The above example sets data from MySQL to text input and text area in HTML. I called GetRecord() at the beginning of body with
<body>
<?php GetRecord(); ?>
</body>
Then I try to make changes to the form and update it with following.
<?php
function UpdateRecord(){
require 'conn.php';
$snowinc = mysqli_real_escape_string($conn, $_POST["SNOW_INC"]);
$incstatement = mysqli_real_escape_string($conn, $_POST["INC_STATEMENT"]);
$priority = mysqli_real_escape_string($conn, $_POST["PRIORITY"]);
$sql = "REPLACE INTO t_summary (SNOW_INC, INC_STATEMENT, PRIORITY)
VALUES ('$snowinc', '$incstatement', '$priority')";
if ($conn->query($sql) === TRUE) {
echo "<br>";
echo "Incident Summary updated successfully.";
echo "<br>";
} else {
echo "<br>";
echo "Error: " . $sql . "<br>" . $conn->error;
echo "<br>";
}
$conn->close();
}
if(array_key_exists('SNOW_INC',$_POST)){
UpdateRecord();
}
?>
Well, his also works well updating the data to DB, but problem happens after I saw a data.
For example, if value in DB shows option 1 then when I view the page it shows option 1, all good. When I change the value to option 2 and save, the value is updated in DB but remained the same in HTML. Obviously if I reload the page, it shows option 2 but I'm trying to avoid that.
Any idea to fix this will be much appreciated. Thank you in advance.
And I know I missed lots of other stuff here. Please ask questions if you want to know more info to fix this.
Thanks again!!
Edit : I have uploaded the site so you can look at the issue better
Instruction :
Go to https://www.mydevplace.xyz/alpha/ and create do a search of any string. It will say record not found and prompt you to create one.
Create a record. Should be self explanatory. Make sure to click Update Incident record. You should get a green confirmation saying Incident Summary updated successfully.
Now on the same page, edit the values to a different strings/records and click the same button. The values is returning to previous value. Thats my problem. If you keep clicking the button, you would see what I mean.
EDIT 2 : I implemented AJAX to update my records and only GetUpdate on first load of the page. All is working well now.
Thanks to all who helped me with this.
Change option value from option1 to option2
<option value="option1">option 2</option>
To
<option value="option2">option 2</option>
Although you have not shared your html, It will be difficult to estimate error.
However I found the below issue with you php codes.
function GetRecord(){
global $getrecordarray;
..
..
..
}
You forgot to define the $getrecordarray as global.
Related
I'm working on an old, out of date webpage which displays data from a database. My task is to enable the selection of some values in order to narrow down what the user is looking at.
I have created a dynamic dropdown list based upon what a certain field within the database is set to. The problem I am having is that once the dropdown selection is made the dropdown resets to default.
I've looked through methods to allow to option to be retained once selected and the page refreshes. However these all require php statements which doesn't work with the method I have used.
Please see the code below. Please ignore $past as this is a variable set for a certain amount of time in the past.
<?php
//Section to fill the Department dropdown
$dropdown = "SELECT `ResponsibleGroup` FROM 'table` WHERE `Change_Start_Time` > '$past' AND `Change_Start_Time` < '$future' AND `Status` NOT LIKE 'Cancelled' AND `Status` NOT LIKE 'New' AND `Status` NOT LIKE 'Re-Scheduling' GROUP BY `ResponsibleGroup` ORDER BY `ResponsibleGroup` ASC";
$dropres = mysqli_query($con,$dropdown);
while($row = mysqli_fetch_array($dropres))
{
echo"<option value='" .$row['ResponsibleGroup'] ."'>" . $row['ResponsibleGroup'] . "</option>";
}
?>
</select>
</form>
The suggestions I've seen suggest putting an if isset PHP statement in the field however, i've not been able to get this to work. I've tried doing exactly as they suggested and just using <?php .... within the echo, which doesn't work. Like the below:
<select name="operator">
<option value="add" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'add') ? 'selected' : ''; ?>>+</option>
I've also tried similar to the above while breaking out of the echo but i can't get that to work either.
Any help or advice on this topic would be greatly appreciated.
Thanks in advance.
I have found the solution for this.
<script type="text/javascript"> document.getElementById('department').value="<?php echo $_POST['department'];?>"; </script>
So got a small problem here, tried so many different solution but it always ends up sending a blank value to the database. So i got a dropdown with two values and one value that is never going to be allowed to make a POST. So if you accidentally click on the "Oppdater" button before selecting a value from the dropdown menu i dont want it to be send, but now it does and just adds a blank value to the database. Example:
<form action="" method="post">
<input type="hidden" name="id" value="' . $row['id'] . '">
<select name="status2" class="endre-status">
<option selected="selected" disabled="disabled">Change status</option>
<option value="Done">Done</option>
<option value="Pending">Pending</option>
</select>
<input type="submit" name="insert2" value="Oppdater">
</form>
Here you can see that i have it selected and disabled and that should mean it will not be sent when i check with isset(), but it still does and puts a blank value in my database.
Here is the code i use to update the database with the new value from the dropdown.
if (isset($_POST['insert2']))
{
$status2 = $_POST['status2'];
$id = $_POST['id'];
$sql2 = ("UPDATE test3 SET status='$status2' WHERE id='$id'");
if (mysqli_query($conn, $sql2)) {
header("Location: index.php");
exit;
} else {
echo "Error: " . $sql2 . "<br>" . mysqli_error($conn);
}}
Here it how it looks:
I have also tried with setting the value of the disabled option to "0" and checking with empty(), but it still sends "0" to the database. If someone can help me that would be very nice. Thank you.
If your options are static you can check it that if value is from your options or not?
in_array function can help you
for example:
$options = array("Done","Pending");
if (in_array($_POST['status2'], $options)) {
in line :
<option selected="selected" disabled="disabled">Change status</option>
you have mentioned selected so by default , the first option would be returned as selected option and it seems logical that it returns 0 .
Suggested solution :
set a break point on insert2 button and leave dropdown empty , then check the returned value . at last try to prevent code side to send that value by control statements such as If
I have a form and a drop down menu for users to select Industy Job Sectors as part of their search, e.g. Accountancy, Construction, Engineering etc.
I've searched this forum for solutions regarding how to remember menu select option values AFTER submit and I'm grateful to have implemented a modified version from the solution I found here:
Simpliest way to remember DropDown selection?
//For example
if(is_post_request()) {
$jobsector['jobsector_id'] = $_POST['jobsector_id'] ?? '';
} else {
$jobsector['jobsector_id'] = '';
}
<div class="form-group">
<label for="jobsector">Job Sector:</label>
<select class="custom-select" name="jobsector_id" id="jobsector_id">
<option value="">Select Sector</option>
<?php
$query = "SELECT jobsectors.id, jobsectors.jobsector_name FROM jobsectors";
$results = mysqli_query($db, $query);
$_SESSION['jobsector_id'] = $jobsector['jobsector_id'];
$_POST['jobsector_id'] = $_SESSION['jobsector_id'];
//loop
foreach ($results as $jobsector): ?>
<option value="<?php echo h($jobsector['jobsector_name']); ?>"
<?php if ($jobsector['jobsector_name'] == $_POST['jobsector_id']){echo " selected";}?>>
<?= $jobsector['jobsector_name']; ?>
</option>
<?php endforeach;
unset ($_SESSION['jobsector_id']); ?>
</select>
</div>
However, I've run in to a problem where the menu select option values that I have, BEFORE the form is submitted, now show a notice/error:
Notice: Undefined index: jobsector_id
Here's a screen grab:
screenshot of undefined index notice
I realise that this will be because the POST value for 'jobsector_id' has not yet been submitted with the form, so my question is how do I get the menu select options to show in the drop down without this error, BEFORE the form is submitted?
I've added a session to store the value of 'jobsector_id' and then made $_POST['jobsector_id'] = $_SESSION['jobsector_id'] and finally unset the session. It all seems to work fine now. Thank you for your suggestions guys!
I have a div statement with two nested divs inside. The first nested div is a form that contains a drop down menu that allows the person to select a basic school subject:
<form id="request" action="<?php echo $_SERVER['PHP_SELF']?> method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<input type="button" value="Find"/>
</div>
</form>
The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:
<div id='div3'>
for ($i=0; $i<count($tutors); $i++)
{
echo "<div>'".$tutors[$i]."'</div><br/>"
. 'Choose me' . "<br/>";
}
</div>
The array is initialized at the very beginning of the php class by connecting to MySQL and then pulling out tutors from the database that are tutor users and tutor in the subject the student user has selected. Again, please forgive me for any bugs, I'm still learning:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query))
{
$tutors[] = $row["Username"];
}
}
else
{
echo "Failed form.";
}
?>
The problem pressing me the most right now is that failed form is always shown on the screen. I suspect this is because the form has been nested inside a div. Is there any way around this? Or is it a different problem(s)?
I'm also wondering if the code will indeed show what I want in the second nested div, or if there are bugs in that too (I'll style it later).
I am basing my solution. on the following assumption. According too these lines from your post. The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:>>>>>> those line were from your post.
Please read the comment in the code carefull. There i explain what i change and suggestions.
This the code
<!--
<form id="request" action="<?php //echo $_SERVER['PHP_SELF']?> method="post">-->
/*
* The line above is wrong and as you may understand by the comments of other user,
you dont need to give anything in the action as you are posting it on the same
* page. so you can delete it. and add this line below one.
*/
<form action="" method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<!--<input type="button" value="Find"/>--->
<input type="submit" value="Find"/>
</div>
</form>
<div id='div3'>
<?php
//I am leaving these php tag for the reference only that you used it in your original code.
//You dont need those lines
?>
</div>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
//$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$con = mysqli_connect("127.0.0.1", "root", "", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = 'tutor' AND Subject ='".$sub."'")or die(mysqli_error($con));
// $tutors = array(); You dont need that line either.
while ($row = mysqli_fetch_assoc($query))
{
$tutors = $row["username"];
echo "<div>'".$tutors."'</div><br/>"
. 'Choose me' . "<br/>";
/*
* **Here is the suggestion**. The link you are giving to
* the user is always going to be SelectedTutor.php.
* I dont think this what you want. you may want to
* show tutor profile or wanna do some thing else when
* somebody click on the link. Lets say you want show
* the tutor profile. Than you have to run another query.
* and should be able to generate link accordingly.
* I am giving you hint how you can do it in case you want to do it.
*/
/*
* you should change that line to this line link one to this
* echo "<div>'".$tutors."'</div><br/>"
* . 'Choose me' . "<br/>";
* If you notcie i added this parth after SelectedTutor.php, this one ?tutor='.$tutors.'
* Than your url will be different when ever user click on the link.
* Hope i did not confused you
*/
}
}
else
{
echo "Failed form.";
}
?>
And you ask why you are getting message of Failed form. In short why your else statement is running. to understand see the expanation below.
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//I removed the code just left the basic shell so you can understand
}
else
{
echo "Failed form.";
}
If you read the above code you will understand why you are getting Failed form message each time when you run the code. You will not get this message when you click on submit.
Reason: Reason is this, in those lines your saying that if Request method is post, than run this bit of code. and Else echo this message out. means whenever your request method is not post run this else statement.
but the thing is that you only sending post request after clicking on the button. before that, there is no post request. so thats why you are getting this message each time you run your script and than it disappear when you click on submit. cause you send the post request.
English is not the first language if i confused you let me know i will explain it again.
Although you have asked for help with PHP/HTML, this is really a job for jQuery/AJAX. Don't worry, though -- it's much simpler than you might think.
The advantage to using AJAX is that you stay on the same page, and the page does not refresh -- but the dropdown selection is sent to a PHP file (that you specify), the MySQL database is consulted, and a response (in HTML) is returned.
Inside the AJAX success function, (did you hear that? Inside the success function!) you receive the HTML returned by the other PHP file and you then plunk the returned HTML into an existing DIV.
Here are some simple examples:
AJAX request callback using jQuery
(1) You would not need to put DIV d2 into <form> tags. Not necessary with AJAX
(2) Your jQuery code would look like this:
<script type="text/javascript">
$('#s').change(function(){
var sub = $(this).val();
$.ajax({
type: 'post',
url: 'my_php_file.php',
data: 'subj=' +sub,
success: function(resp){
$('#div3').html(resp);
}
});
});
</script>
The above script can be placed anywhere in the document, or in the head tags, or included in a separate document.
(3) You must reference the jQuery library, as per the first example in the "AJAX request callback..." link.
(4) There will be no need for the Find button, because the code will fire as soon as the dropdown value is changed. It takes microseconds to communicate with the server and stick the list of tutors in the div3 div.
(5) The div3 div must already exist on the page (but it can be empty).
(6) The PHP file (called my_php_file.php in the code above) would be exactly as you wrote, except that it would create an output variable containing the HTML to be plunked into the div3 div. For example:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
$sub = $_POST['subj'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno()){
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query)) {
$tutors[] = $row["Username"];
}
$out = '';
for ($i=0; $i<count($tutors); $i++) {
$out .= '<div>' .$tutors[$i]. '</div><br/>
Choose me<br/>
';
}
}else{
$out = "Failed form.";
}
echo $out;
?>
All above code is untested, but could work...
So this should be my last question for this entire project. I've made the employee timecard pages. Works great. I'm trying to make them a review/change page per timecard. Basically the initial review page pulls up the timecards they've submitted. They select Review. It carries the ID number to a review page, and I call upon the ID number to display all the info from that timecard into the new timecard html/php form. (Basically its the exact same form they used to submit, however I've echo'd the values as the option already)
When I do update though it's not only carrying over the echo'd value. It's only Updating any changes they make, and in fact deleting everything else. Below is a snippit of just one drop-down list (all over non drop-down's update fine. This is just for drop down lists where the data is contained in the DB.
<select name="starttime" id="input_6" style="width:150px">
<option value="" selected><?php echo $stime ?></option>
<?php
$result = mysql_query("SELECT time FROM selTime ORDER BY id");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"" . $row['time'] . "\">" . $row['time'] . " </option>";
}
?>
</select>
So what happens with this code. Is when they open the review page They would see their start time as they submitted it. If they leave it alone, and not change anything and push submit after changing something else. The starttime actually UPDATES as blank. If they change the starttime to a value it DOES submit the change. Is there something in this code that I can change that will submit the echo'd value, instead of just displaying it?
I believe the issue is with this line of code:
<option value="" selected><?php echo $stime ?></option>
Although you set it as "selected" the selected element has the value of "" (empty). Try changing it to:
<option value="<?php echo $stime; ?>" selected="selected"><?php echo $stime; ?></option>
If they dont change this select list item, and submit the page directly, the selected item is the first one with the value="", so this will update in the database with blank ( null).
You need to give your fist item a value of date time now. This code here:
<option value="DATETINMENOW" selected><?php echo $stime ?></option>