4

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.
pattyd
  • 5,927
  • 11
  • 38
  • 57
  • http://stackoverflow.com/questions/12166494/execute-sql-query-on-button-click does not help, I do not want to submit the whole form... – pattyd May 21 '13 at 00:01
  • 2
    You'd need to send an HTTP POST/GET request to be able to tell the PHP server when the button is clicked, and have PHP call any database functions. Most of the time this is achieved using a HTML form, but not necessarily. – Qantas 94 Heavy May 21 '13 at 00:04
  • Why was this closed? It is not difficult to understand – pattyd May 21 '13 at 14:48

3 Answers3

8

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>
samayo
  • 16,163
  • 12
  • 91
  • 106
  • Thanks alot! That is exactly what I meant! I haven't tested this yet, but It looks right! Thanks! – pattyd May 21 '13 at 12:26
  • testing now.... there are some errors in your code: change eles to else and mysq to mysql testing now,... – pattyd May 21 '13 at 21:47
  • Ok, sorry about that. – samayo May 21 '13 at 21:58
  • ok this seriously isnt working..... could you please incorperate this into my code that is in my question? I really appreciate it. – pattyd May 21 '13 at 23:27
  • thanks for your help so far, i cant get it to work with my code, could you please show with my code? thanks – pattyd May 21 '13 at 23:34
  • @pattyd ok, but give me some time. I will try to create it in my localhost, and i'll give you when I finish. – samayo May 22 '13 at 00:31
  • 2
    @pattyd Ok, I just remembered like 10 minutes ago, and tested this script before I sleep. It works, but, I may build something better and that works with Javascript/Ajax tomorrow and will give you, if ur still interested. cause, I enjoy make those little scripts. – samayo May 22 '13 at 02:06
  • ok thanks! All i need is something that works, i definatly would prefer PHP, even if it is a big mess, AJAX/js works too thx! – pattyd May 22 '13 at 14:50
  • PHPNOOB IS THE MAN! THX SOOOOO MUCH DUDE! The only error in that code was that the delete button had to be nested in a form: `
    buttonhere
    ` THANKS AGAIN!!!! I hope to see you again on another SO forum!
    – pattyd May 22 '13 at 16:14
  • I will keep the old answer as the accepted answer though, it doesnt really make a difference cuz they are both yours! Thanks! – pattyd May 22 '13 at 16:15
  • also, if you want the button value to be something other than the ID you can turn the button into a hidden field, and have a new submit button with a value of Delete, or what ever you want it to say. – pattyd May 22 '13 at 16:35
  • 1
    glad it worked for you :),try to add a message saying 'are you sure u want to delete this/that user' functionality, and it will be good, I have an empty room on [ajax](http://chat.stackoverflow.com/rooms/30213/ajax) :( drop me a message, if u want – samayo May 22 '13 at 16:41
  • okay thanks! I don't think i will add the confirmation yet. How do i send you a message? Sorry, kinda new to SO! – pattyd May 22 '13 at 16:46
  • I am not sure, if you have enough reps to chat, but you can follow the link i gave you above, and just post message there, if not u have to wait a little bit, until you earn more reps – samayo May 22 '13 at 16:51
  • yeah i can chat, what link are you talking about? – pattyd May 22 '13 at 16:56
  • click right [here](http://chat.stackoverflow.com/rooms/30213/ajax) – samayo May 22 '13 at 16:59
5

You can do something like this to save a value from an input/submit btn.

<!-- your html form -->
<form action="POST">
    <input type='text' name='username' />
    <input type='text' value='submit' />
</form>



<?php 

// your php code

if($_POST && isset($_POST['username'])){

    $db = new \PDO('......'); // enter your db details

    $stmt = $db->prepare("INSERT INTO table (username) VALUES (?)");
    $result = $stmt->execute(array($_POST['username']);

    echo $result->rowCount() ? 'Username saved in db' : 'Unknown error occured'; 

}
samayo
  • 16,163
  • 12
  • 91
  • 106
  • oh! that looks right! thanks, testing now! – pattyd May 21 '13 at 00:03
  • and this works on the same page as the button, correct? – pattyd May 21 '13 at 00:03
  • @pattyd as long as your button name is `submit` yes, it will, just try writting anything inside the field and echo it inside the if(isset) – samayo May 21 '13 at 00:04
  • ok, above the button, or below? – pattyd May 21 '13 at 00:05
  • The both. You fill something in the above, and press the submit button – samayo May 21 '13 at 00:06
  • gotcha, one minute please – pattyd May 21 '13 at 00:07
  • that worked! thanks! I will accept the answer as soon as Stack Overflow allows! Thanks Again!!! – pattyd May 21 '13 at 00:11
  • No problem. Feel free to ask me more if you have anything on this subject, maybe one more question.. I love helping :) – samayo May 21 '13 at 00:12
  • Okay I have one more..... I do this inside a loop okay? so i want to delete the row that the button is clicked on.... but it deletes all of the records, not just the one record that is clicked! I may have to sign off, but I can post more soon, if needed! Thanks so much! – pattyd May 21 '13 at 00:16
  • You can do the same, inside the `if` statement, create another if, and check if something is pressed with specific name(button name) then, use that value to delete a record. I didn't clearly undestand the question though – samayo May 21 '13 at 00:20
  • I mean I am looping over the table rows result, printing all the rows to the screen. Beside each row is a button that says delete.... when i press it i tell it to execute echo "hi"; and it echoes that as many times are there are rows.... I only want the function to be called once... once for the row it is pressed on.... does that give better detail? Or should I share more? – pattyd May 21 '13 at 00:55
  • Give me some codes, as I am answering another question, I am not in focus. I undestood some, but not all. sorry – samayo May 21 '13 at 01:03
  • okay.... i will add in an edit – pattyd May 21 '13 at 01:04
  • PHP Noob: its in the edit, thx! – pattyd May 21 '13 at 01:12
  • give me a minute, never built a delete by row query, but it is simple possible to create a quick one. – samayo May 21 '13 at 01:22
  • 1
    @pattyd check my other answer, for clarity sake, I have made another one. I hope it gives you some idea, if not you can re-ask by use the code, and some SO experts will help you out. just make sure to post clear questions – samayo May 21 '13 at 01:32
1

Use an AJAX library to issue a request to a server-side script that executes your query. Put this as your onClick() handler in Javascript, and presto, Bob's your uncle!

hd1
  • 33,938
  • 5
  • 80
  • 91