ss888
ss888

Reputation: 1748

PHP/MySQL run query on button press/click

Was wondering if it's possible to run/re-run a mysql query when a button/link is pressed/clicked?

Basically, I run a query that limits the results to the first 7, with a button below the results to show more results. When the button is clicked/pressed, I need to re-run the query and set the limit to, say 20.

Any help/advice on how to do this would be greatly appreciated. Thanks in advance, S.

Upvotes: 3

Views: 2750

Answers (2)

Steve Claridge
Steve Claridge

Reputation: 11080

The code to run the query and produce the results is on the server and the button is on the browser so you need some way to communicate back to the server that you want more results. You can either use an Ajax call and update your page's contents dynamically or just make it a <a> link and GET another page with more results on.

You already have code that returns 7 results and show them on a page - let's say your page to show the seven is https://www.blah.com/show. You could add a parameter to your page that accepts the number of results to show, e.g. https://www.blah.com/show?num=7. Now instead of hardcoding the SQL to read seven results, you first read the parameter and use that number in your query. The link to show more results can now be <a href="https://www.blah.com/show?num=20">Show more</a>

The Ajax option could be similar, but instead of using a <a> to retrieve the new page from the server you would call it using (in jQuery) $.ajax() and would insert the results into your page. This is slightly more complicated than the first example.

Upvotes: 4

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

Just thought of answering in a better way. We can do it in multiple ways. Let's say if you want to use a Bootstrap button (very common ask). What you can do is execute using three ways:

  1. Redirection
  2. AJAX Calls
  3. Forms

Using Redirection:

<button class="btn btn-primary" onclick="location.href='query.php?run=true';">Run SQL</button>

And then in PHP, you can do:

<?php
  // query.php
  if ($_GET["run"] == "true") {
    $sql = "INSERT INTO contacts_requirements_tbl (employeeid, DocumentName, ExpirationTime,type, exempt) SELECT $id, Docname, ExpirationTime, type, exempt FROM contacts_requirements_tpl ";
    mysqli_query($connection_object, $sql);
  }
?>

Without a redirection using AJAX calls, you can use this way:

<button class="btn btn-primary" onclick="fetch('query.php?run=true');">Run SQL</button>

Or using a Form:

<form action="query.php?run=true">
  <button class="btn btn-primary" type="submit">Run SQL</button>
</form>

Upvotes: 0

Related Questions