I have a PHP form which saves user data to a MySQL database.
I want to show the user which information is held about them and display it in a form in order for them to update or edit the values.
I have a problem in getting the user’s saved data from the database in a PHP loop and show that to user in order for them to update or edit it.
Below is the piece of code:
<?php
$id = $_GET['id'];
$conn = mysqli_connect('localhost', 'phpmyadmin', 'Test@2000', 'user');
$sql1 = "SELECT * FROM usr WHERE id='$id'";
$result = mysqli_query($conn, $sql1);
$row = mysqli_fetch_assoc($result);
?>
<fieldset><label>Birthday</label>
<select name="birthday">
<?php
for ($i = 1300; $i <= 1397; $i++) {
echo "<option >$i</option>";
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
I want to show into the form’s Select input the birthday value that user selected originally, in order to edit or update by user.
3
Answers
The
<select>
children elements<option>
does support aselected
tag to indicate that it was the selected value, so by adding the selected tag like so<option value='1' selected>
you can have that as the selected value.You’ll also want to probably add the
$i
value into your option element to ensure that the values are being submitted properly.Mozilla documentation:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select
I have edited your code in this way.
Hope this helps, thanks.
A.) WITH PDO MODULE
It is best practice today to use prepared statements to avoid SQL injection. This is done through the PDO object.
Set for select the autocomplete=”off” attribute, because Firefox apparently has a bug with the selected=”selected” that needs this to be set.
See if it is the user’s birthday, we can use intval to compare.
B.) Please at least try option A.), but if it doesn’t work: