Php – Execute PHP function on image onClick without loading the page

htmlmysqlphp

I have this HTML code. I want to click on the image and execute the PHP code without loading the PHP page. It will execute in background and update filed in the database.

How can I do this in a reliable way without loading the PHP page?

If I need to use form, how can I use it here? I have tried it but failed.

html code

<table>
<td align="center">
        <div class="round-button">
            <a href="viewStatus.php">
                <img name="myImg" src="images/City.png" alt="Home" />
            </a>
        </div>
    </td>
</table>

php code

<?php

    $connection = mysqli_connect("localhost", "root", "");
    if (!$connection) {
        die("Error: " . mysqli_error());
    }

    $db_select = mysqli_select_db($connection, "myimageda");
    if (!$db_select) {
        die("Error: " . mysqli_error());
    }
    mysqli_query($connection, "UPDATE `myDB` SET `state`=1 WHERE `id` = 1");

    ?>

Best Solution

here is your answer in a simple and easiest way

HTML

<table>
<td align="center">
        <div class="round-button">
            <a href="#" onClick=rec('USE ANY VALUE HERE FOR IDENTITY')>
                <img src="images/City.png" />
            </a>
        </div>
    </td>
    ....
</table>

then use javascript to call that function

<script type="text/javascript">
    function rec(id) {
       $('#newCode').load('viewStatus.php?id=' + id);
    }        
</script>

and write your PHP code like below

<?php

    $connection = mysqli_connect("localhost", "root", "");
    if (!$connection) {
        die("Error: " . mysqli_error());
    }

    $db_select = mysqli_select_db($connection, "myimageda");
    if (!$db_select) {
        die("Error: " . mysqli_error());
    }
    $ver = 'YOUR IDENTITY';
    if($ver == CONDITION) {
       mysqli_query($connection, "UPDATE `myDB` SET `state`=1 WHERE `id` = 1");
    }
    else {
    ...
    }
    ...
    ?>
Related Question