Home > Mobile >  How to execute a mysql command on button click from a website [duplicate]
How to execute a mysql command on button click from a website [duplicate]

Time:09-29

I'm creating a simple website, but before I go further, I want to make sure it can connect to my database and execute commands. Right now, I have a single button that I want to tell the database to execute a query (presumably using a php script embedded in html). The query is to just insert the current time into a table. Can someone please check what I've got to see if it's useable or not? Thanks.

<body>

    <button name="Log time" type="submit">Log the Time</button>

    <form action='' method='POST'>
        <?php
            mysql_connect('hostname', 'username', 'password');
            mysql_select_db('databasename');
            $query = "INSERT INTO Log_Time(Button_Time) VALUES (current_timestamp)";
        ?>
    </form>

</body>

CodePudding user response:

Your form will make a POST action to the current URL (action=''), then in PHP, you will check the variable $_POST to get the value or you can know the form is submitted.

<?php
if (isset($_POST['Logtime']))
{

    echo 'Executed SQL';

    mysql_connect('hostname', 'username', 'password');
    mysql_select_db('databasename');
    $query = "INSERT INTO Log_Time(Button_Time) VALUES (current_timestamp)";

}
?>

<form action='' method='POST'>
    <button name="Logtime" type="submit">Log the Time</button>
</form>

CodePudding user response:

There are a lot of ways to do this but the way you are doing it is wrong..

one way you can do it right would be add an id to your button and control the click with javascript inserting the data PHP or any other backend language to your database you can not directly write SQL queries in HTML.. any way doing it in PHP would be as follows..

    <body>

        <?php
        if (isset($_POST)) {
            mysql_connect('hostname', 'username', 'password');
            mysql_select_db('databasename');
            $query = "INSERT INTO Log_Time(Button_Time) VALUES (current_timestamp)";
        }
        ?>
        <form action='' method='POST'>
            <button name="Log time" type="submit">Log the Time</button>
        </form>

    </body>

to improve my answer more you can use pdo instead of using the old MySQL function here is a reference link you can go and follow...

https://www.php.net/manual/en/book.pdo.php

  • Related