Pages

Sunday, November 18, 2012

Update/Edit MySQL data using PHP

I stumbled upon this kind of scenario in one of my projects. Just want to share this way of editing MySql data using PHP.

I have a file named get_info.php that has a combobox with the data I needed to edit.



<table>
<form name="edit" method="POST" action="edit.php">

<select name="edit_combo">
<?php

#query the data inside the sample_table and display it inside the combobox
$query = "select sample_data_id, first_data, second_data from sample_table";
$q = mysql_query($query);

while($data = mysql_fetch_array($q))
{
?>
<option name="optionsample" value="<?=$data["sample_data_id"]?>"> <?=$data["first_data"]?>, <?=$data["second_data"]?> </option>
<?php
}
?>
</select>
<tr>
<td><input type="submit" name="combo_edit" /></td>
</tr>
</form>
</table>

The selected option's value will then be displayed to another php file named edit.php.


....
<td><input type="hidden" name="sample_id" value="<?php echo $data["sample_data_id"];?>" /></td>
<td>First: <input type="text" name="first" value="<?php echo $data["first_data"];?>" /></td>
<td>Second: <input type="text" name="second" value="<?php echo $data["second_data"];?>"/></td>
....

Then the values will be passed again to another file edit_info.php for the update in the database.

$first_inp = $_POST["first"];
$second_inp = $_POST["second"];
$id_inp = $_POST["sample_id"];

#values will update the the sample_table in the sample_db database
mysql_query("update sample_table set first_data='$first_inp', second_data='$second_inp' where sample_data_id = '$id_inp'");

There are other ways to do an update to database, but this does the job.:)

Here's the download link if you want to try this example.


No comments:

Post a Comment