Home >Backend Development >PHP Tutorial >Example demonstrating how to call a PHP function when a button is clicked
The central content of this article is as mentioned in the title, which is to teach you how to call PHP functions when clicking a button. In fact, there are many ways to call PHP functions. In addition to performing this operation by clicking a button, you can also use Ajax, JavaScript and JQuery call PHP functions; but this article mainly introduces the button-oriented PHP function calling method.
Without further ado, here are two ways to implement how to call a PHP function when a button is clicked (using an HTML button to call a PHP function).
Method 1:
Note: Create an HTML form document containing HTML buttons. When the button is clicked, the POST method is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function is called.
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style="text-align:center;"> <h1 style="color:red;"> PHP中文网 </h1> <h4> 如何通过点击按钮调用PHP函数? </h4> <?php if(array_key_exists('button1', $_POST)) { button1(); } else if(array_key_exists('button2', $_POST)) { button2(); } function button1() { echo "这是按钮1被选中"; } function button2() { echo "这是被选中的按钮2"; } ?> <form method="post"> <input type="submit" name="button1" class="button" value="按钮1" /> <input type="submit" name="button2" class="button" value="按钮2" /> </form> </body> </html>
The effect is as follows:
Method 2: This program uses the isset() function to call the PHP function.
Note: The following example is only based on the POST method: The code is as follows:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style="text-align:center;"> <h1 style="color:#17c4ff;"> PHP中文网 </h1> <h4> 如何通过点击按钮调用PHP函数? </h4> <?php if(isset($_POST['button1'])) { echo "这是按钮1被选中"; } if(isset($_POST['button2'])) { echo "这是被选中的按钮2"; } ?> <form method="post"> <input type="submit" name="button1" value="按钮1"/> <input type="submit" name="button2" value="按钮2"/> </form> </body> </html>The effect is as follows:
PHP Video Tutorial"~ Come and learn!
The above is the detailed content of Example demonstrating how to call a PHP function when a button is clicked. For more information, please follow other related articles on the PHP Chinese website!