0

I'm fairly new to PHP, JS and other web development oriented languages.

I have a big table that contains info directly retrieved from the database, at the end of each row I would like to add a button that deletes that line from the database.

Since there are a lot of entries in this table, I would like the button to call a function that erases the data concerning this row, but I can't seem to find how to even open a connection with the database from a script

<table>
<tr class="titles">
<td> <strong> column1 - id </strong> </td>
<td> <strong> column2 </strong> </td>
<td> <strong> column3 </strong> </td>
<td> <strong> column4 </strong> </td>
<td> <strong> etc... </strong> </td>
<td> </td>
</tr>

<?php 
$query = 'SELECT * FROM my_table';
$req = $bdd -> query($query);
$n = 0;
while ($data = $req -> fetch())
{
echo '<tr>';
echo '<td>' . $data['id'] . '</td>';
echo '<td>' . $data['column2'] . '</td>';
echo '<td>' . $data['column3'] . '</td>';
echo '<td>' . $data['column4'] . '</td>';
echo '<td>' . $data['column5'] . '</td>';

echo '<td> <button type="button" id="' . $data['id'] . '" onclick=\"delete_line(this.id);\" > Delete </button> </td>';
echo '</tr>';
}
?>
</table>

<script>
function delete_line(value) {
//*fucntion that execute the query : "DELETE FROM my_table WHERE id = value LIMIT 1;
}
</script>

Should the script modify a chunk of php and then call the same page (like a form) so it's executed??

GePu
  • 320
  • 2
  • 13
  • 1
    Go read up on AJAX ... – CBroe Aug 15 '17 at 12:10
  • 1
    Your client-side code would make an AJAX request to server-side code (likely a "page" of its own, but one that interacts via JSON instead of HTML). This server-side code would perform your server-side actions (such as interacting with a database) and then respond back with some result to the client. – David Aug 15 '17 at 12:11
  • @David, what I'm struggling with is how to send the proper information with this AJAX request. Meaning I want to erase the contents of THAT line and that line alone. Without of course compromising the rest of the data to SQL injection and whatnot. Thanks for your answers. – Francisco Arandano Aug 17 '17 at 08:15
  • @FranciscoArandano: It looks like the value you want to send is the `id` value of the button being clicked. It's certainly uncommon to use an `id` attribute for this, but not entirely invalid. Your AJAX request would just need that value and the server-side code would use that value in the SQL query to identify the record to delete. – David Aug 17 '17 at 09:35

0 Answers0