简体   繁体   中英

Using MySQL With an HTML Page Using Javascript

This might be a stupid question but i'm looking for a method to post and get from a MySQL database using JavaScript on a HTML web page. As I'm looking to make a small game and wanted to save information in real time. I can do it using PHP but of course this isn't going to be real time more on page load.

Thanks in advance. Tim.

PHP Example

<?
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['btnP1Login'])) {
            $myFile=fopen("P1Status.txt","w") or exit("Can’t open file!");
            fwrite($myFile, 'Online');
            fclose($myFile);
            header('Location: lobby.php');
        }
        if (isset($_POST['btnP2Login'])) {
            $myFile=fopen("P2Status.txt","w") or exit("Can’t open file!");
            fwrite($myFile, 'Online');
            fclose($myFile);
            header('Location: lobby.php');
        }
    }
?>

<html>
    <body>
        <div id="player1">
            <p>Player 1 - Offline</p>
            <form method="post" action="index.php">
                <input type="submit" name="btnP1Login">
            </form>
        </div>

        <div id="player2">
            <p>Player 2 - Offline</p>
            <form method="post" action="index.php">
                <input type="submit" name="btnP2Login">
            </form>
        </div>
    </body>
</html>

You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:

var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close; 

A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.

And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)

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