Skip to content
Advertisement

check a table in database when a form is saved in php

I have a form which has a save button as shown below:

<form method="post" id="myform" style="text-align: left;">
<div style="text-align:center;">
    <button onclick="saveButton()" type="submit">Save</button>
</div> 
</form>

In that form, what I want to achieve is when a user press the save button then it should check a table in the database.

The table which I want to get it checked is list_users. list_users has 5 columns:

(1) user_name
(2) open 
(3) read_access
(4) write_access  
(5) LastActivity

When any user login (let's user UserA) then:

read_access => 1
write_access => 1

When another user (let's say UserB) login at the same time then

UserA
read_access => 1
write_access => 0

UserB
read_access => 1
write_access => 1

What I want to achieve is when write_access => 0 then the user should not be allowed to save the form meaning on pressing save button it should check write_access column in list_users table. If the value is 0 in write_access column, then the user should not be allowed to save the form.

This is what I have tried:

function saveButton(e) {
    <?php
    $stmt = $connect->prepare("SELECT write_access FROM list_users WHERE user_name=?");
    $stmt->bind_param('s', $_SESSION['user_name']);
    $stmt->execute();
    $result2 = $stmt->get_result();
    $write_access = $result2->fetch_object();
    if($write_access->write_access != 1) { ?>
    alert('You cannot save the form');
    e.preventDefault();
    <?php } ?>
}

I am getting the alert message but the form is still getting saved. I am wondering what changes I should make in the code so that with the alert message the form should also not get saved.

Advertisement

Answer

One approach to solve this is using onsubmit on the form instead of onclick on the submit button

<form method="post" id="myform" style="text-align: left;" onsubmit="return saveButton()">

And on the javascript function, use return false

function saveButton() { // remove e parameter
    <?php
    $stmt = $connect->prepare("SELECT write_access FROM list_users WHERE user_name=?");
    $stmt->bind_param('s', $_SESSION['user_name']);
    $stmt->execute();
    $result2 = $stmt->get_result();
    $write_access = $result2->fetch_object();
    if($write_access->write_access != 1) { ?>
    alert('You cannot save the form');
    return false; // instead of e.preventDefault()
    <?php } ?>
}

Here is the scenario :

Know that onsubmit="return false" will cancel the form submit,

then using return saveButton() and returning false on saveButton function will also cancel the form submit

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement