简体   繁体   中英

PHP: execute function upon clicking a button

I am building a PHP & mySQLi CRUD app.

Inside a functions.php file I have a function that takes care of deleting individual users :

function delte_single_user() {
 if (isset($_GET['id'])) {
    global $con;
    $user_id = $_GET['id'];
    $sql = "DELETE * FROM `users` WHERE `id`= " . (int)$user_id . ";";
    $result=mysqli_query($mysqli, $sql);
 }
}

In the file that displays the users, I have the CRUD "buttons":

<ul class="list-inline">
    <li><a title="View user" href="view_user.php?id=<?php echo $arr['id']; ?>"><span class="glyphicon glyphicon-user"></span></a></li>
    <li><a title="Delete user" onclick="delte_single_user()"><span class="glyphicon glyphicon-trash"></span></a></li>
</ul>

As you can see, I am trying to fire the delte_single_user() upon clicking the delete button, JavaScript style (I am new to PHP but I have significant experience JavaScript). But it does not work.

So, what is PHP's closest alternative to my use of delte_single_user() ?

NOTE: I am trying to avoid creating a delete_user.php fie as it would not be useful.

Thank you!

You cannot call a PHP function from JS directly.

You need to make an ajax call or redirect to the PHP script that handles the delete.

The same as you are doing with linking to the view_user.php script.

You could create a new script called delete_user.php and pass it the id of the user using GET. Inside this script put the function above and call it.

<a title="Delete user" href="delete_user.php?id=SOME_ID">DELETE</a>

EDIT:

Consider having a user.php script that handles everything user related. like:

user.php?action=view&id=USER_ID
user.php?action=delete&id=USER_ID

This way you have a single file, and in user.php you could do:

if(isset($_GET['action']) && $_GET['action'] == 'delete') {
    // check id
    // delete the user AND redirect the user back (if not using ajax)
} elseif (/* check if action=view */) {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM