I hope someone can help me figure this out as I'm new to PHP and MySQL. But basically, what I'm trying to do is to pull the data from the database and populate the dropdown box and textbox, and so I can update the value in the textbox.
This is the table structure:
id | hf_name | hf_price
------------------------
AI | test 1 | 123
AI | test 2 | 123
So let's say I wanna update "test 1" price, I would select "test 1" in the dropdown selection and update the price in the textbook.
This are my code:
<form class='data_form' action='data/food_update.inc.php' method='post'>
<select>
<?php while ($row = mysqli_fetch_array($result)):; ?>
<option><?php echo $row[1];?></option>
<?php endwhile;?>
</select>
<input type='number' name='hf_price' placeholder='$'>
<button type='submit'>UPDATE</button>
</form>
Include:
<?php
//CONNECTION TO MySQL
include '../dbh.php';
//VARIABLES
$hf_name = $_POST['hf_name'];
$hf_price = $_POST['hf_price'];
$by_user = $_SESSION['Fname'];
$up_date = date('Y-m-d');
$sql = "SELECT hf_name FROM hotfoods";
$result = mysql_query($conn, $sql);
?>
Thanks!
Try changing the option to
<option value="<?php echo $row[2];?>"><?php echo $row[1];?></option>
Where I'm assuming $row[2] variable contains the hf_price value.
but for this you need to change your id datatype into int,
$query = "select * from tablename";
$result = mysqli_query();
<select id="nameID" name="hf_name">
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['id']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>
This will be fine when you fetch details but it does not update any value because for this you need to use Ajax or Jquery for update on Select, let me to try it.
Ajax
$("#nameID").onchange(function(){
var id = $("#id").val();
$.ajax(
url: "update.php",
type: "POST",
data: {'id'=id},
success: function(){
alert("ok");
});
});
Try this it might work.
$query = "select * from tablename";
$result = mysqli_query($query);
<select>
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['hf_name']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>