I have a following php file to display SELECT data from database
$connection = mysql_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD) or die("Pripojeni se nezdarilo" . mysql_error());
mysql_select_db('svatepole');
$sql = "SELECT * FROM novinky";
$result = MySQL_Query($sql, $connection);
while($zaznam = MySQL_Fetch_Row($result)):
echo "<form class='newsholder'>";
echo "<input value='$zaznam[1]'>";
echo "<input value='$zaznam[2]'>";
echo "<textarea>$zaznam[3]</textarea>";
echo "<input id='prime' attr='id' value='$zaznam[0]'>";
echo "<div class='buttonsholder'>";
echo "<button id='deletebutton'>Smazat</button>";
echo "<button>Upravit</button>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
and I'm trying to add jquery ajax
$('#deletebutton').on('click', function(){
var idVal = $(this).parent().parent().find('#prime').val();
alert(idVal)
$.post("deleterecord.php",
{id:idVal}
);
});
to find the row's ID and pass it to the DELETE file, so the row gets deleted on click.
$connection = mysql_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD) or die("Pripojeni se nezdarilo" . mysql_error());
$id = $_POST['id'];
if(! $connection )
{
die('Could not connect: ' . mysql_error());
}
$sql = "DELETE FROM novinky WHERE id = $id"
;
mysql_select_db('svatepole');
$retval = mysql_query( $sql, $connection );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($connection);
However, I can't get this to work. According to Chrome console, there is an event handler attached only to the FIRST row, although the database contains a lot more. Also the added alert only pops out on the click of the very first button.
Any idea, what am I doing wrong and how to pass the data correctly to the DELETE query?
Thanks.
mysql_*functions anymore, they are deprecated. See Why shouldn't I use mysql_* functions in PHP? for details. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial.htmlspecialcharswhen outputting to HTML to prevent XSS.