通过PHP插入SQL数据库

时间:2015-04-17 20:05:39

标签: java php sql sql-insert

我的Java代码生成如下链接:

addscore.php&name=Namedd&score=0&hash=b61249d0207e4734879578733a86c3d6

PHP文件(addscore.php)应该使用这些信息并使用sql查询将其插入数据库。

addscore.php:

<?php
         $db = mysql_connect("host", "root", "password") or die('Could not connect: ' . mysql_error());
         mysql_select_db("db1") or die('Could not select database');

         $score = (int)$_GET['score'];
         $hash = $_GET['hash'];
         $name = mysql_real_escape_string($_GET['name'], $db);
         $timestamp = date("Y-m-d H:i:s");
         $secretKey="mySecretKey";

         $real_hash = md5($score . $hash . $secretKey);

         if($real_hash == $hash) {
             $query = "INSERT INTO highscores (id, date, score, name) VALUES (NULL, '$timestamp', '$score', '$name')";
             $result = mysql_query($query) or die('Query failed: ' . mysql_error());
         }
?>

Java代码提供错误消息,无法向服务器提交分数。如果我尝试打开给定的网址(见上文),我会收到Not found错误。

更新 Java代码:

        String hash = "";
        String name = nameText.getText();
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update((name + score + HASH_SALT).getBytes());
            byte byteData[] = md.digest();

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            hash = sb.toString();
        } catch (Exception e) {
            hash = "";
        }


        try {
            String urlParameters = PARAM_NAME + name + PARAM_SCORE + score + PARAM_HASH + hash;
            URL url = new URL(HIGHSCORES_ADD + urlParameters);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.getInputStream();
            urlConnection.disconnect();
        } catch (Exception e){
            Gdx.app.log( "HighScores", "Could not submit score" + e.getMessage());
        } finally {
            ((Game)Gdx.app.getApplicationListener()).setScreen(new MainMenu());
        }

1 个答案:

答案 0 :(得分:2)

你的地址应该是

addscore.php?name=Namedd&score=0&hash=b61249d0207e4734879578733a86c3d6

请注意网址

中的第一个&

在您的Java代码中,请确保?HIGHSCORES_ADD之间有urlParameters

修复后如果保存数据仍有错误 一个好主意是将$查询保存在文本或日志文件中,并尝试在phpmyadmin中检查查询

你必须注意的另一件事是 你的插入是通过PHP而不是java!更新您的问题主题