简体   繁体   English

php表单未在mySQL中更新数据库

[英]php form is not updating database in mySQL

I have created a table to display the top 10 high scores for a game by the users. 我创建了一个表来显示用户对游戏的前10个最高得分。 i am trying to create a form which allows the user to enter their new high score in the form, hit submit, then the database is updated and the new leaderboard with the newly entered high score is displayed. 我正在尝试创建一个表格,该表格允许用户在表格中输入他们的新高分,点击提交,然后更新数据库,并显示具有新输入的高分的新排行榜。 but when i go to change the high score the database isnt updated and the table doesnt change. 但是,当我更改高分时,数据库未更新,表也未更改。 this is really frustraiting me and if anyone knows why this could be happening and could give some advice that would be great. 这真的使我受挫,如果有人知道为什么会发生这种情况,并且可以提出一些很棒的建议。 my code is below/ 我的代码在/

<?php

class DatabaseManager
    {
        private $servername = "localhost";
        private $username = "root";
        private $password = "";
        private $dbname = "sokodatabase";
        private $dbc;

        function __construct() {
            $this->dbc = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname);
        }

        function __destruct() {
            mysqli_close($this->dbc);
        }

        public function SelectHighScores(){
            // Create a query for the database
            $query = "
                    SELECT username, highScores, rankNo
                    FROM users, leaderboardhighscores
                    WHERE users.id = leaderboardhighscores.userId
                    ORDER BY highScores desc
                    LIMIT 10";

            // Get a response from the database by sending the connection
            // and the query
            $response = @mysqli_query($this->dbc, $query);

            // If the query executed properly proceed
            if($response){
                echo '<table>
                <tr><td><b>Rank</b></td>
                <td><b>Username</b></td>
                <td><b>High Score</b></td></tr>';


                // mysqli_fetch_array will return a row of data from the query
                // until no further data is available
                while($row = mysqli_fetch_array($response)){
                    echo '<tr><td>' .
                    $row['rankNo'] . '</td><td>' .
                    $row['username'] . '</td><td>' .
                    $row['highScores'] . '</td><td>';

                    echo '</tr>';
                }

                echo '</table>';
            } else {
                echo "Couldn't issue database query<br />";
            }
        }
    }
?>    

my html with php to create form... 我的html与php建立表格...

                <div class = "leaderboard">
                        <?php

    // Get a connection for the database

    require_once('../sokodatabase.php');
    $manager = new DatabaseManager;
    $manager->SelectHighScores(); 

    //if(isset($_POST['submit'])){

          //require_once('../sokodatabase.php');  
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    $query = "
                    UPDATE leaderboardHighScores
                    SET highScores=".$_POST["highScores"].", rankNo=".$_POST["rankNo"]."
                    WHERE userId=".$_POST["userId"];

                //var_dump($_POST); 
                //echo $query;

                @mysqli_query($this, $query);
            }
    //}       


    ?>

    <form method="post" action="highScores.php">
        high score <input type="text" name="highScores"/>
        rankNo <input type="text" name="rankNo"/>
        userId <input type="text" name="userId"/>
        <input type="submit" value="Submit">
    </form>
                </div>

First off, for security measures, always sanitize user input before using in a query. 首先,为了安全起见,在使用查询之前,请务必先清除用户输入的内容。

Second, you also don't need the @ before mysqli_query - unless your trying to suppress any and all erorrs/warnings thrown by the function. 其次,您也不需要在mysqli_query之前使用@ -除非您试图抑制该函数引发的任何和所有错误/警告。

Third, try and use the same cases for your SQL; 第三,尝试对SQL使用相同的情况; you used leaderboardhighscores in the class, and then leaderboardHighScores in the second part of your code; 你用leaderboardhighscores的类,然后leaderboardHighScores在你的代码的第二部分; I don't know which one's the real name in the database but will assume for former is since that is working as you say. 我不知道数据库中的真实姓名是谁,但是假设以前的名字是真实的,因为这确实如您所说。 I'm saying this because case-sensitivity could result an issue, please read MySQL docs on this matter. 我说这是因为区分大小写可能会导致问题,请阅读MySQL文档

Fourth, you are using $this outside of a class on a page where it has no meaning (if not another). 第四,您在没有意义的页面上的类之外使用$this (如果没有其他含义)。

Add this function to the DatabaseManager class: 将此函数添加到DatabaseManager类:

public function SetHighScores($uid, $score, $rank) {
    $uid   = mysql_real_escape_string($uid);
    $score = mysql_real_escape_string($score);
    $rank  = mysql_real_escape_string($rank);

    $query = "UPDATE leaderboardhighscores SET highScores='{$score}', rankNo='{$rank}' WHERE userId='{$uid}';";

    return mysqli_query($this->dbc, $query);
}

And then this would go on your page: 然后这将出现在您的页面上:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $manager->SetHighScores($_POST['userId'], $_POST['highScores'], $_POST['rankNo']);
}

Also, you should look into PDO_MYSQL , would be a better option to go for, but I understand what you're doing is good for learning the basics I guess. 另外,您应该研究PDO_MYSQL ,这将是一个更好的选择,但是我知道您在做什么对我猜测的基础知识很有帮助。

Try this then 然后试试这个

$result = mysqli_query($manager->dbc, $query);
if ( ! $result ) {
    echo 'Error code ' 
         . mysqli_errno($manager->dbc)
         . ' Error message ' 
         . mysqli_error($manager->dbc);
}

As $manager is the variable that is holding your DatabaseManager class's object instance within the scope of the code that is executing, and that object has a property called dbc that contains the database connection handle. 由于$ manager是在正在执行的代码范围内保存DatabaseManager类的对象实例的变量,并且该对象具有名为dbc的属性,该属性包含数据库连接句柄。

As @x3ns says in his/her comment you will also need to change the DatabaseManager code like this 正如@ x3ns在他/她的评论中所说,您还需要像这样更改DatabaseManager代码

class DatabaseManager
    {
        private $servername = "localhost";
        private $username = "root";
        private $password = "";
        private $dbname = "sokodatabase";

        public  $dbc;    //<-- change here

So that you can access that property from outside the object itself. 这样您就可以从对象本身外部访问该属性。

This is a quick fix but to be honest you would be better stopping and reading @x3ns's answer and applying most if not all of his/her suggestion. 这是一个快速解决方案,但老实说,您最好停止阅读@ x3ns的答案,并应用大部分(如果不是全部)他/她的建议。

Although I would like to add one more. 尽管我想再添加一个。

It is very bad practice to generate output directly from a class method as you have in public function SelectHighScores() 像在public function SelectHighScores()一样,直接从类方法生成输出是非常糟糕的做法

Directly echoing from a method totally destroys the ability to subclass and amend the activity of that method. 直接从方法中回显完全破坏了继承和修改该方法的活动的能力。 It is far better to generate the output into a variable and return that variable. 最好将输出生成为变量并返回该变量。 Then if I want to subclass your method I have the option of amending its result in some way if I need to. 然后,如果我想对您的方法进行子类化,则可以选择在需要时以某种方式修改其结果。

Try replace: 尝试替换:

@mysqli_query($this, $query);

With: 带有:

@mysqli_query($this->dbc, $query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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