-3

我正在尝试使用平面文件创建一个评分系统(我知道,我也更喜欢使用 mysql)。我已经设法创建了足够多的变量,以便将变量从游戏中提取出来(用户名和分数)并放入所述文本文件中。我还可以在格式化表格中输出这个文本文件。但是我无法让分数按任何顺序排序 - 理想情况下我想要降序。在网上搜索后,我能找到的最好的方法是在附加的代码中,但是目前这似乎并没有真正做任何事情。我知道这可能是一个愚蠢的错误,但我可以用一双新的眼睛来看看它。非常感谢,哈利

<?php
echo '<table width="5%" border="5"><tr><th>Your Score</th><th>Your Name</th></tr>';
echo '<tr><td>'.$_POST["m_score"].'</td><td>'.$_POST["name"].'</td></tr>';
echo '</table>';
echo "<br />";


$data=$_POST["m_score"].",".$_POST["name"].",";
      $filename = "./highscores.txt";
      $handle = fopen($filename, "a");

      if (!$handle)
      {
           print "There were problems opening the file";
           exit();
      }

      fwrite($handle, $data);
      fclose($handle);

      $handle = fopen($filename, "r");
      $datain = fread($handle, filesize($filename));
      $value = explode(",",$datain);        
      $row = floor(count($value)/2);
      $count = 0;


      $filename = file("./highscores.txt");
      sort($filename);
      file_put_contents("./highscores.txt", implode($filename));


    echo '<table width="5%" border="1"><tr><th>Top Scores</th><th>Top Users</th></tr>';
    for ($i=0;$i<$row;$i++)
    {
        echo '<tr>';
        for($x=0;$x<2;$x++){
            echo "<td>$value[$count]</td>";
            $count++;
        }
        echo "</tr>";
    }
    echo '</table>';

    fclose($handle);

?>
4

1 回答 1

0

我写了一个你可以学习的例子,如果你真的不想让一个成熟的 mySQL 服务器处理你的数据,那么这里是你如何使用内置的 sqlite2 函数来完成它,超级简单,对任何小数据都非常有用sql 类型总是比平面文件查询更快,插入更容易。希望能帮助到你:

<?php
//Create db or return connection
$db = setup('scores.db');

//form so you can enter data
echo '<h1>Put Score demo:</h1>
<form method="POST" action="">
  <p>Name: <input type="text" name="name" size="20"></p>
  <p>Score: <input type="text" name="m_score" size="20"><input type="submit" value="Submit"></p>
</form>';
//Validate score as a number and the name is set
if(isset($_POST['m_score']) && is_numeric($_POST['m_score']) && !empty($_POST['name'])){

    $name = $_POST['name'];
    $m_score = $_POST['m_score'];

    //Put result into database
    database("INSERT INTO scores (id,name , m_score) VALUES (NULL,'".sqlite_escape($name)."',".(int)$m_score.")",'put',$db);

    //Show users score
    echo '<table width="5%" border="5"><tr><th>Your Score</th><th>Your Name</th></tr>';
    echo '<tr><td>'.htmlentities($m_score).'</td><td>'.htmlentities($name).'</td></tr>';
    echo '</table>';
    echo "<br />";

}else{
    //Get Results from database
    $result = database("SELECT DISTINCT name, m_score from scores ORDER BY m_score DESC",'get',$db);

    //Show global score
    echo '<table width="5%" border="1"><tr><th>Top Scores</th><th>Top Users</th></tr>';
    foreach ($result as $row){
        echo '<tr>';
        echo "<td>".htmlentities($row['m_score'])."</td>";
        echo "<td>".htmlentities($row['name'])."</td>";
        echo "</tr>";
    }
    echo '</table>';
}

/**
 * Simple function to setup the sqlite database or return a connection to that db
 *
 * @param string $db_name
 * @return mixed (Connection or setup success)
 */
function setup($db_name){
    global $db;
    if(file_exists($db_name)){
        if(isset($db)){return $db;}
        return sqlite_open($db_name, 0666, $error);
    }
    $db = sqlite_open($db_name, 0666, $error);
    (!$db)?die($error):null;
    //Create new db
    $query ="CREATE TABLE scores (id INTEGER PRIMARY KEY, name TEXT(255), m_score INTEGER)";
    $ok = sqlite_exec($db, $query, $error);
    (!$ok)?die("Cannot execute query. $error"):null;

    echo 'Setup completed, Refresh page.';
    die;
}

/**
 * A simple sqlite CRUD with U & D missing ;p
 *
 * @param (sql query) $query
 * @param (put|get) $do
 * @param (Connection resource) $db
 * @return result
 */
function database($query,$do,$db){
    $error=null;
    $return=null;
    switch($do){
        case "get":
            $result = sqlite_query($db, $query, $error);
            if (!$result) die("Cannot execute query {$query} ". $error);
            $i=0;
            while ($entry = sqlite_fetch_array($result, SQLITE_ASSOC)) {
                foreach($entry as $key=>$value){
                    $return[$i][$key]=$value;
                }
                $i++;
            }
            return $return;
            break;
        case "put":
            $result = sqlite_exec($db, $query, $error);
            if ($result==false){ die("Cannot execute statement {$query} ". $error);}else{ return sqlite_changes($db);}
            break;
        default:
            die("Missing 2nd argument for database function.");
            break;
    }
    return true;
}

/**
 * Function to escape user input for db
 *
 * @param unknown_type $data
 * @return unknown
 */
function sqlite_escape($data) {
    if(is_array($data)){return array_map("sqlite_escape_string", $data);}
    return sqlite_escape_string($data);
}
?>
于 2012-05-15T15:57:54.877 回答