i'm writing a plugin and want to change entities based on a sql query.

function showTest()
    var result= "<button onClick='query(\"wp_users\")'>users</button>" .
                "<button onClick='query(\"wp_posts\")'>posts</button>" .
                "<div class='results'/>" . 
                     function query(table) {
                          var sql = "SELECT * FROM " + table;
                          // query sql and display results in div
     return result;                 
add_shortcode("test", "showTest");

How do i perform the query and display the results?

  • You are mixing up JavaScript and PHP. You can't put PHP/MySQL in a script tag or trigger with onclick attributes. Jan 31, 2018 at 14:58
  • well that is my problem, my query(table) is (and has to be) a js-function and i think i need to call php-functions to query sql
    – Ginso89
    Jan 31, 2018 at 15:06
  • You need to perform an AJAX request in JS to the server, which can then perform a PHP/MySQL request to the database and return the result. Teaching all this though A. Has nothing to do with WordPress and B. Is far too broad a topic for a Q&A format. Jan 31, 2018 at 15:17

1 Answer 1


You should gotten return from SQL first. And then print results. Use $wpdb class for SQL queries. If you wanna use native SQL queries something like this might helps you

$result = mysql_query("SELECT * FROM table");
$result_array = mysql_fetch_array($result, MYSQL_ASSOC);

But it`s very bad idea. Use $wpdb with preparing.

  • but this is php. the query has to happen after the button is pressed, so i have to that in the js function. How do i do that?
    – Ginso89
    Jan 31, 2018 at 14:36
  • You can`t create SQL query on native JS or jquery. Angular or node.js can doing sql queries. Also you can send jquery.ajax request on your server, build your query and send back sql response. Jan 31, 2018 at 14:41
  • can u give me an example, how i do that?
    – Ginso89
    Jan 31, 2018 at 14:47
  • i have tried so many examples i found googling and nothing worked
    – Ginso89
    Jan 31, 2018 at 15:33
  • Read about jQuery.ajax(); it`s very simple. jQuery.ajax({ url: 'your_php_script_url', type: 'post' (or get), data: {your data from front to backl-end}, success: function(response){ // Function calls when ajax request successfully returned } }); in php script do your sql script and by echo command send data back. Jan 31, 2018 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.