通过onClick javascript函数使用PHP更新MySql数据库

7 javascript php mysql ajax

我正在创建一个网络游戏,用于学习针对儿童的新单词.

我有一组四个链接,每个链接显示从我的数据库中检索到的特定单词和线索,我需要检查已选择的单词是否与该线索的正确单词匹配.

我知道我需要使用javascript因为onClick功能,我可以成功检查所选单词是否与正确的单词匹配.但是,如果单词匹配正确,我需要更新数据库中保存的分数,因此我需要使用php.

从我可以收集到的这意味着我必须使用AJAX,但我找不到任何人使用AJAX onClick链接然后更新数据库的好例子.

我试图这样做......但它可能是完全错误的,因为我无法让它正常工作:

//This is my link that I need to use in my game.php file where $newarray[0] is that answer I want to check against $newarray[$rand_keys]

<a onClick=originalUpdateScore('$newarray[0]','$newarray[$rand_keys]')>$newarray[0]</a>
Run Code Online (Sandbox Code Playgroud)

//我在score.js文件中尝试ajax

var xmlHttp;

function originalUpdateScore(obj,corr){
    xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
    alert ("Browser does not support HTTP Request");
    return;
}

if(corr == obj){

var url="getscore.php";
//url=url+"?q="+str;
//url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
//xmlHttp.open("GET",url,true);
xmlHttp.open(url,true);
xmlHttp.send(null);

    alert('Correct');

}
else
{
    alert('AHHHHH!!!');
}

window.location.reload(true);
Run Code Online (Sandbox Code Playgroud)

}

function stateChanged() 
    { 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
        document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
    } 
}
function GetXmlHttpObject()
{
    var xmlHttp=null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        //Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
return xmlHttp;
Run Code Online (Sandbox Code Playgroud)

}

//attempting to update the database in a getscore.php file

<?php
//$q=$_GET["q"];
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");

$sql= "UPDATE `temp` SET `tempScore`= `tempScore`+1 WHERE (temp.Username='$_SESSION[logname]')";

$showsql = "SELECT `tempScore` FROM `temp` WHERE (temp.Username='$_SESSION[logname]')";
$result = mysqli_query($con, $showsql);

echo "$result";

mysqli_close($con);
?>
Run Code Online (Sandbox Code Playgroud)

小智 17

我强烈建议正确学习AJAX - 它不会花费你很多年,但会帮助你理解你能做什么,不能用它做什么.

通过AJAX从网页更新数据库非常常见.我建议使用jQuery(JavaScript库)简化JavaScript开发.这是一个很好的介绍jQuery和AJAX 在这里.

基本上jQuery会做的就是为你编写很多样板代码.你最终写的是这样的:

function updateScore(answer, correct) {
  if (answer == correct) {
    $.post('updatescore.php');
  }
}

...

<a onclick="updateScore(this, correct)" ...> </a>
Run Code Online (Sandbox Code Playgroud)

你在这里做的是在答案正确时向updatescore.php发送POST请求.

然后,在您的updatescore.php中,您只需要拥有像您已经做过的PHP代码,这将更新数据库中的分数.

显然你可以做比这更复杂的事情,但希望这足以让你开始.