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.
The <select> children elements <option> does support a selected 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.
<?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 == $row['birthdayYear']) ? 'selected="true"' : '') . ">$i</option>";
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
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.
<?php
$id = $_GET['id'];
$host = 'localhost';
$username = 'phpmyadmin';
$password = 'Test#2000';
$db_name = 'user';
$conn = new PDO('mysql:host:=' . $host . '; dbname=' . $db_name, $username, $password);
$sql1 = "SELECT * FROM usr WHERE id = :id;";
$stmt = $conn->prepare($sql1);
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<fieldset><label>Birthday</label>
<select name="birthday" autocomplete="off">
<?php for ($i = 1300; $i <= 1397; $i++) {
if($i === intval($row['birthdayYear'])){
echo "<option selected='selected'>$i</option>";
} else {
echo "<option>$i</option>";
}
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
B.) Please at least try option A.), but if it doesn't work:
<?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" autocomplete="off">
<?php for ($i = 1300; $i <= 1397; $i++) {
if($i === intval($row['birthdayYear'])){
echo "<option selected='selected'>$i</option>";
} else {
echo "<option>$i</option>";
}
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
Related
In my database I have 2 tables:
To insert data, I have a form that populates dropdown options from the table formulation. This is what the insert form for formulation dropdown looks like:
<?php
$formulation = '';
$query = "SELECT * FROM formulation";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$formulation .= '<option value="' . $row["formulationID"] . '">' . $row["formulation_name"] . '</option>';
}
?>
<select>
<option value="">Select formulation</option>
<?php echo $formulation; ?>
</select>
Now I am working on the ‘Update’ form. But my question is how can I populate the ‘Formulation’ field dropdown with the data from the formulation table (like as the insert form) but pre-selected with the existing formulation value for the name from the items table? Like this image below:
I am having problem with how I should build the form. How should I proceed with this form?
<?php
$output = array('data' => array());
$sql = "SELECT * FROM items";
$query = $connect->query($sql);
while ($row = $query->fetch_assoc()) {
$output['data'][] = array(
$row['name'],
);
}
echo json_encode($output);
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
<label>Formulation</label>
<select >
<!--What should be the codes here? -->
</select>
</div>
<button type = "submit">Save changes</button>
</form>
Thanks in advance for your suggestion.
Note: I'm not a user of mysqli so maybe there will be some error, but you will get the idea. This will not tackle the update part, just the populate part
Since you are editing a certain item, I will assume that you have something to get the item's itemID.
<?php
$sql = "SELECT * FROM items WHERE itemID = ?";
$query = $connect->prepare($sql);
$query->bind_param("s", $yourItemID);
$query->execute();
$result = $query->fetch_assoc();
$itemName = $result['name'];
$itemFormulation = $result['formulation_fk'];
//now you have the name and the formulation of that certain item
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text" value="<?php echo $itemName; ?>"><br>
<label>Formulation</label>
<select >
<?php
$query = "SELECT * FROM formulation";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['formulationID']; ?>" <?php echo ($row['formulationID'] == $itemFormulation) ? 'selected' : ''; ?>>
<?php echo $row['formulation_name']; ?>
</option>
<?php
}
?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>
I changed the code to better suit the problem, there may be typos, just comment for clarification
If I have understand Your question... You have to put Your result into a string. For example:
<?php
$output = array('data' => array());
$sql = "SELECT * FROM items";
$query = $connect->query($sql);
$option = '';
while ($row = $query->fetch_assoc()) {
$name=$row['name'],
$option.='<option value="$name">$name</option>'
}
echo json_encode($output);
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
<label>Formulation</label>
<select >
<?=$option?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>
I hope to be of help
This should do the trick:
<?php
$itemsSql = "SELECT * FROM items WHERE itemId = 5";
$itemQuery = $connect->query($sql);
$item = $itemQuery->fetch_assoc();
$formulationsSql = "SELECT * FROM formulation";
$formulationsQuery = $connect->query($sql);
$formulations = $itemQuery->fetch_assoc();
?>
<form action="updateItem" method="POST">
<div>
<label>Item Name</label>
<input type="text" value="<?= $item[0]['name']; ?>"><br>
<label>Formulation</label>
<select>
<?php foreach($formulations as $formulation){
echo '<option value="'. $formulation['formulationId'].'">' .
$formulation['formulation_name'] . '</option>';
} ?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>
i need insert new location to row with the name i choose from my drop down.
How can i connect between the name and the location?
<?php
$connect = mysqli_connect('localhost', 'root', '', 'test');
$query = 'SELECT * FROM test';
$res = mysqli_query($connect, $query);
echo "<select name='testform'>";
while($row=mysqli_fetch_assoc($res)){
echo "<option value=>$row[name]</option>";
}
echo "</select>";
?>
<html>
<form action="indexx.php" method="POST">
<br>Locatio name:<input type= "text" method="POST"><BR>
<input type="submit" value="Insert" method="POST">
</form>
</html>
Check if the form was submitted by giving it a name and checking if it is set in your PHP code. If it is set, it means that the user submitted your data entry form. Perform an INSERT statement with the value the user entered.
Sidenote: input-tags don't have an attribute "method". You can remove those.
You might want to read about the lifecycle of a PHP script and the usage of the $_POST array in PHP. The syntax of the INSERT statement can be found in numerous language specs or tutorials.
I think you mixed things up a bit and wrote the following code for you. Please tell me if this explains it a bit more.
The code you require
<?php
if (isset($_POST['submit'])) {
$connect = mysqli_connect('localhost', 'root', '', 'test');
$query = "UPDATE test SET location_name='".$_POST['new_location']."' WHERE id='".$_POST['location']."' LIMIT 1";
$res = mysqli_query($connect, $query);
if (!$res) {
die("Something went wrong");
}
}
// This is the code to load the select options
$connect = mysqli_connect('localhost', 'root', '', 'test');
$query = 'SELECT * FROM test';
$res = mysqli_query($connect, $query);
$options = array();
while($row = mysqli_fetch_assoc($res)) {
$options[] = $row;
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
<select name="location">
<option value="0">--- Select an option ---</option>
<?php foreach ($options as $option): ?>
<option value="<?= $option['id'] ?>"><?= $option['name'] ?></option>
<?php endforeach; ?>
</select><br />
New name: <input type="text" name="new_location"><br />
<input type="submit" name="submit" value="Update" />
</form>
<?php
if (isset($_POST['submit'])) {
$connect = mysqli_connect('localhost', 'root', '', 'test');
$query = "UPDATE test SET location_name='".$_POST['new_location']."' WHERE id='".$_POST['location']."' LIMIT 1";
$res = mysqli_query($connect, $query);
if (!$res) {
die("Something went wrong");
}
}
// This is the code to load the select options
$connect = mysqli_connect('localhost', 'root', '', 'test');
$query = 'SELECT * FROM test';
$res = mysqli_query($connect, $query);
$options = array();
while($row = mysqli_fetch_assoc($res)) {
$options[] = $row;
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
<select name="location">
<option value="0">--- Select an option ---</option>
<?php foreach ($options as $option): ?>
<option value="<?= $option['id'] ?>"><?= $option['name'] ?></option>
<?php endforeach; ?>
</select><br />
New name: <input type="text" name="new_location"><br />
<input type="submit" name="submit" value="Update" />
</form>
I want to selected items from mytable when using three tables and &_GET another id to open in this page so i want to use where and where to complete fetch my data by using two roles .
<?php
$sel = "SELECT * FROM `informations` where `cate_id` =".$_GET['info_id'];
$done = mysql_query($sel);
?>
<form action="" method="post" enctype="multipart/form-data">
<label for="location"></label>
<select name="location" id="location"><?php
$sel_cate = "SELECT * FROM locations";
$done_cate = mysql_query($sel_cate);
while($get_cate = mysql_fetch_array($done_cate)){
echo '<option value="'.$get_cate['id'].'">'.$get_cate['location'].'</option>';
$loc=$get_cate['id'];
}
?>
</select>
<input type="submit" name="go" id="go" value="Go">
<input type="submit" name="all" id="all" value="Show All...">
</form>
<?php
if(isset($_POST['go'])){
$sel ='SELECT * FROM `pharmacies` WHERE `cate_id` ="'.$_GET['info_id'].'" || `location_id` = "'.$_POST['location'].'"';
?>
I tried this code and when isset($_POST['go']) variable $sel got $_GET['info_id'] and $_POST['location'] values. Query generated without errors, and must fetch information.
I not see mysql_query in your: if(isset($_POST['go'])). Maybe you forget query:
if(isset($_POST['go']))
{
$sel = 'SELECT * FROM `pharmacies` WHERE `cate_id` ="'.addslashes($_GET['info_id']).'" or `location_id` = "'.addslashes($_POST['location']).'"';
$selRslt = mysql_query($sel);
while($row = mysql_fetch_array($selRslt))
{
var_dump($row);
}
}
I can't seem to be able to update any records except the first one.
I am not sure how to modify any of the displayed records.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'][0];
$type = $_POST['type'][0];
// if I echo $id & $type, it only gives me the first record.**
mysql_query("
UPDATE membership_type
SET mt_type ='$type'
WHERE mt_id = '$id'"
);
}
?>
ALl of this is within the same php page.
<form name=form action='' method='post'>
<?php
$result=mysql_query("SELECT * FROM membership_type;");
while($rows=mysql_fetch_array($result))
{ ?>
<input size=35 class=textField type=text name='type[]' value='<?php echo $rows['mt_type']; ?>'>
<input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
<input type=submit value="Update">
<?php
}
?>
How do I edit any of the displayed records by simply clicking Update button???
First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:
<?php
// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');
// Check if there's POST request in this file
if($_POST){
foreach($_POST['m_id'] as $id => $type){
$query = "UPDATE membership_type
SET mt_type = '".$type."'
WHERE mt_id = '".$id."'";
// Try to exec the query
$mysqli->query($query) or die($mysqli->error);
}
}else{
// Get all membership_type records and then iterate
$result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>
<form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
<?php while($row = $result->fetch_object()){ ?>
<input size='35'
class='textField'
type='text'
name='m_id[<?php echo $row->mt_id ?>]'
value='<?php echo $row->mt_type; ?>'>
<input type='submit' value="Update">
<?php } ?>
</form>
<?php } ?>
Third: In order to add more security (this code is vulnerable), try mysqli_prepare
Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].
Replace it. Hope this works.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$i = 0;
foreach($id as $mid) {
mysql_query("UPDATE membership_type
SET mt_type='".mysql_real_escape_string($type[$i])."'
WHERE mt_id = '".intval($mid)."'") OR mysql_error();
$i++;
}
}
?>
Try this :
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$loopcount = count($id);
for($i=0; $i<$loopcount; $i++)
{
mysql_query("
UPDATE membership_type
SET mt_type ='$type[$i]'
WHERE mt_id = '$id[$i]'"
);
}
}
You HTML was malformed and you were passing as an array but then only using the first element. Consider:
<form name="form" action="" method="post">
<?php
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
<input type="submit" value="Update">
</form>
Then the server script:
<?php
if(isset($_POST["action"]) && $_POST["action"] == "Update"){
foreach($_POST['m_ids'] as $mt_id => $mt_type)
mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));
}
There are other things you could be doing here, eg. prepared statements, but this should work.
I have this code and I'm trying to put the selected state in a subcat table.
So far it returns an empty value. I'm not sure if this is clear or not, but all I want is: select a state from the select option and submit it. I want to get the selected state name into my table subcat.
enter <?php
include("connect.php");
$state = $row['states']; //Select name
if (isset($_POST[submit])){
$query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form> here
Thanks
Change $state = $row['states'] to $state = $_POST['states']
<?php
include("connect.php");
if (isset($_POST[submit]))
{
$state = $_POST['states']; //Select name
$query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>"; // if you want to
//get the name into table, then use like this
//echo "<option value='$row[name]'>$row[name]</option>"; or
//echo "<option>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form>
Try this:
enter <?php
include("connect.php");
if (isset($_POST[submit])){
$state = $_POST['states'];
$query = "INSERT INTO subcat (sub_name) VALUES ('".mysql_real_escape_string($state)."')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo '<select name="states" id="states">
<option value="">Select a state</option>';
while ($row = mysql_fetch_assoc($sql)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
<input type="submit" name="submit" value="Continue" />
</form> here
Dont forget to use mysql_real_escape_string to prevent SQL injections. I have replaced $state = $row['states']; with $state = $_POST['states'];
I dont know where u got $row from...
The above will insert the states name into the database.