Home > Enterprise >  How to change SQl value with a button click on PHP
How to change SQl value with a button click on PHP

Time:06-08

Don't know how much code is actually needed so let me know!

I have this project I'm developing and I'm doing the admin-end on PHP. It uses SQL and the admin can pretty much update, remove and promote to administrator normal users(what I can't do).

SQL

 CREATE TABLE User (
    UserID int NOT NULL,
    Username varchar(50) NOT NULL,
    Email varchar(255) NOT NULL,
    Password varchar(255) NOT NULL,
    Image varchar(255) NOT NULL,
    Type varchar(255) NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=latin1;

The field type is either admin/user. What I want to do is on a button click I change the value from user to admin.

I was thinking of using the onclick JS function but I have no idea how this can be achieved. Like follows:

<a onclick='.$row["Tipo"].'= admin" >Promote</a>

Thanks for the read, any help is welcome!

CodePudding user response:

To help your endeavours given that you "don't have the slightest clue on how JS works" I put together a quick and simple demo of how you might use a hyperlink ( not a button as per the question though a similar approach can be used for buttons! ) and dataset attributes might be combined to toggle between 2 states. That toggling between states allows you to then choose between he stated admin/user roles when implemented with other logic correctly. As there is no HTML form nor a desired method you can use this with either a regular form ( as shown ) or with Ajax ( not shown )

The demo only changes the value of a form element and also the text within the hyperlink

document.querySelector('a.btntgl').addEventListener('click',function(e){
  let role=document.forms.adduser.role;
  
  this.dataset.tmp=this.textContent;
  this.textContent=this.dataset.alt;
  role.value=this.dataset.alt;
  this.dataset.alt=this.dataset.tmp;
  
  this.removeAttribute('data-tmp');
});
.btntgl{
  text-transform:capitalize
}
<form name='adduser' method='post'>
  <!-- loads of other fields -->

  <input type='text' name='role' value='admin' /><!-- should be hidden maybe? -->
  <input type='submit' />
</form>

<a class='btntgl' href='#' data-alt='user'>admin</a>

CodePudding user response:

$(document).on('click', '#btntgl', function(e){
    e.preventDefault();
    let typeValue = $(this).date('id');

        $.ajax({
            method: "POST",
            url: "update.php",
            data: {type:typeValue},
            success: function (msg) {
                if(msg === "ok") {
                    alert("success");
                } else {
                   alert("error");
                }
            }
        });
});
<a id="btntgl" data-id="<?php echo $row['Tipo'];?>" >Promote</a>

the update.php will contain your update statement to update the table.

  • Related