Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute mysql on button click [closed]

PHP:
How would I execute SQL when a button is clicked? Would I do it with the JavaScript onClick() function, or some other way? I am trying to do this inside of a loop, and only execute the sql on the row that the button is clicked on... Thanks!

Code for @PHPnoOb to help: Okay, so now I have all of that sorted out, but when the button is clicked it executes once for each row... not just once for the row the button was clicked on! I only want the row that the button was clicked on to be queried... my code:

while($row = mysqli_fetch_array($result)) {

//FAULTY CODE!!! EXECUTES ONCE FOR EACH ROW!
//I WANT IT TO ONLY EXECUTE FOR THE ROW THE
//BUTTON WAS CLICKED ON

if(isset($_POST['delete'])){
echo "You clicked on: ".$row['subject'];
//eventually i will have sql query up here
}
//echo all the results into a table... messy
echo"

<tr><td><div align='center'><font color='grey'>".$row['date']."</font></div></td><td><div align='center'> ".$row['sender']."</div></td><td><div align='center'> ".$row['subject']."</div></td><td><div align='center'><input type='button' value='open' onClick='window.alert(\"On ".$row['date']." ".$row['sender']." wrote:\\n".$row['message']."\")'/></div></td><td><div align='center'><form  method='post'><input type='submit' value='delete' name='delete'/></form></div></td></tr>

";

}

echo '</table>'; //ends the table.
like image 590
pattyd Avatar asked Dec 09 '22 15:12

pattyd


1 Answers

Update: 2017

This answer is outdated, please use better library like PDO to accomplish the below feature.


Ok, just copy/paste the whole code in a plain PHP text. It works, I tried it just now. All you need is a table called test, with fileds id,username, or you can costumize the script, however you like. and don't forget to change databse password, username details..

<form action='' method='POST'>
<?php

mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$query  = "SELECT * FROM users";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
    echo "  To delete user   <b>" . $row['username'] . "</b>  Click on the number <input type='submit' name='delete' value='" . $row['id'] . "' /><br/>";
}

if (isset($_POST['delete'])) {
    $user = $_POST['delete'];
    $delet_query = mysql_query("DELETE FROM users WHERE id = $user ") or die(mysql_error());

    if ($delet_query) {
        echo 'user with id ' . $user . ' is removed from your table, to refresh your page, click' . '<a href=' . $_SERVER["PHP_SELF"] . ' > here </a>';
    }
}
?>
</form>
like image 183
samayo Avatar answered Dec 17 '22 18:12

samayo