Shea Lavington Shea Lavington - 6 months ago 10
PHP Question

Update a table of information on a button click

I have a table which will select information from a database and display it, I'm wondering if anyone can provide a code for me to update a column on the click of a button?

Example Table: (Access=Boolean)

ID - Name - Access
---------------------------
1 - John - 1
---------------------------
2 - Ben - 1
---------------------------
3 - Terry - 0
---------------------------


My exisiting button is based on bootstrap,

<button type=\"button\" id=\"passed\" class=\"btn btn-success btn-flat\"><i class=\"fa fa-check\"></i></button>
<button type=\"button\" id=\"insufficient\" class=\"btn btn-danger btn-flat\"><i class=\"fa fa-times\"></i></button>


I was hoping for something like this, ONCLICK button1 Run $Allowed SQL
ONCLICK button2 Run $NotAllowed SQL

$allowed = mysqli_query($conn," UPDATE users SET Access = "1" WHERE id = '27' ");
$notallowed = mysqli_query($conn," UPDATE users SET Access = "0" WHERE id = '453' ");

Answer

You can use a form with a post method and a submit type of buttons with named attributes and use those in a conditional statement.

I.e.:

Sidenote: I removed the escaped quotes, as I was not sure if those were already set inside an echo.

HTML form:

<form method="post" action="handler.php">

    <button type="submit" name="passed" id="passed" class="btn btn-success btn-flat"><i class="fa fa-check"></i></button>
    <button type="submit" name="insufficient" id="insufficient" class="btn btn-danger btn-flat"><i class="fa fa-times"></i></button>

</form>

PHP:

<?php 

// db connection

if(isset($_POST['passed'])){

    $allowed = mysqli_query($conn," UPDATE users SET Access = "1" WHERE id = '27' ");

}

if(isset($_POST['insufficient'])){

    $notallowed = mysqli_query($conn," UPDATE users SET Access = "0" WHERE id = '453' ");

}

Footnotes:

When running an UPDATE query, it's best to use mysqli_affected_rows() for absolute truthness.

Otherwise, you may get a false positive.

Comments