Reputation: 72
I would like to delete a row from mysql database. The row I would like to delete is the 'selected item' in the combobox.
My code so far:
$sql = "SELECT data_id FROM projects";
$result = mysql_query($sql);
echo "<select name='data_id '>";
echo "<option selected>Please select...</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['data_id '] . "'>" . $row['data_id'] . "</option>";
}
echo "</select>";
?>
<tr><td><input type="submit" name="delete" value="Delete" id="delete"></td></tr></tr></table>
<?php
//delete selected item from projects table...
?>
The combobox is showing all the items from my projects table. When I select an item, then click on 'delete' I would like to delete that item from the table.
Any help will be appreciated.
Upvotes: 0
Views: 6685
Reputation: 160
first off all you are using type submit and by that you need a form,and when you use option you need to set a value or the option 1 2 3
if you want to delete a particular row in the database and let say the id is 1 so it is the first row do it like this
if(isset($_GET['to_be_deleted']))
{
$id=mysql_real_escape_string($_GET['to_be_deleted']);
mysql_query("DELETE FROM name_table where id='$id'");
}
if my answer is not good please ask me with more details
Upvotes: 0
Reputation: 669
I did not get why do they suggest you to use ajax, while you can make simple form
<form method="post" action="">
<tr><td>
//SOME PHP where you obtain from the database the data_id (this you have done already)
<option value='" . $row['data_id '] . "'>" . $row['data_id'] . "</option>
//
<input type="submit" name="delete" value="Delete" id="delete">
</td></tr>
</form>
and on same page at the top before HTML
<?php
if(isset($_POST['delete']) {
//and now mysql DELETE FROM .... WHERE id = $_POST['data_id']
//dont forget to escape and use mysli instead of mysql
}
?>
Btw. dont use mysql_* its deprecated, + escape everything in mysql + dont use fetch_array when you dont need an array, fetch_assoc is fine ;) Hope that helps.
Upvotes: 1
Reputation: 146
Your logic should be:
At top of script before html, check for POST values from form if they exist, use the variables to delete the appropriate database value use header('location') back to the same page to reload the page (so value is removed from form below)
where you have your select box, make that a form, action= same page, method = post
tomorrow I will post example code if you have not worked it out by then
Upvotes: 0