简体   繁体   中英

How To Display a random row from database on button click?

I'm a beginner, and I want to know how to display a random row from database On BootstrapButton Click.

here's my code:

<h3 id="myHeader">Press the button below to display a name</h3>

        <script>
    function displayResult() {
        document.getElementById("myHeader").innerHTML =<?php $row["Name"] ?>;
    }
    </script>

    <button type="button" class="btn btn-primary" onclick="displayResult()">Another One</button>

You'll have to create a PHP page which fetches a random item from a table and outputs the result

SELECT * FROM table ORDER BY RAND() LIMIT 1

Then, on button click, you want to create an Ajax request to the page and display the results. I would use JQuery for this

$.ajax({
    url: "random.php",
    success: function(response){
        $('#myHeader').html(response);
    }
})

You need to do a php script and fetch that row , and use ajax to get that response

$.ajax({
    url: "path_to_your_file",
    success: //your_Logic
  })

Now you have send a request after opening your php script and wait for the response.

var your_request= new XMLHttpRequest();
your_request.open("GET","your_file.php="data_var_name_in_php="+data ...);
your_request.send();
your_request.onreadystatechange = function result() {
  document.getElementById("myHeader").innerHTML = your_request.responseText;
}

I advise you to test your php script first to check what you can get as a response text on your local server. See Ajax Documentation for more information : http://api.jquery.com/jquery.ajax/

You can connect to your database MySQL via JS using this library : http://www.mysqljs.com/

and this is the code to connect :

MySql.Execute(
"mysql.yourhost.com", 
"username", 
"password", 
"database", 
"select * from Users", 
function (data) {
    console.log(data)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM