• User

    Principiante - chiedo info per creare una tabella dal database

    Premetto che so praticamente 0 di php e mysql, ho utilizzato solo CMS preimpostati.
    Attualmente sto sviluppando dei games che hanno un collegamento ad internet per inserire gli HISCORE, tramite uno script predisposto, che ho inserito in un sito di prova, il GIOCO si collega al server (database) e aggiorna i vari campi. Questo è lo script che crea la tabella :

    [php]<?
    // Get Configuation file
    require("config.php");

    // Connect to your server
    $db=mysql_connect($host,$user,$pass) or die (mysql_error());
    @mysql_select_db($dbname) or die (mysql_error());
        
    //////////////////////////////////////////////////
    // Check for the existing table if its not found create it
    // This is really just here to make the life of new users of the script eaiser
    // They won't have to go thru the script and create the table
    /////////////////////////////////////////////////
    
    if(!mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$tname."'")))
    {
    $query = "CREATE TABLE `$tname` (`id` int(11) NOT NULL auto_increment,`gameid` varchar(255) NOT NULL,`playername` varchar(255) NOT NULL,`score` int(255) NOT NULL,`scoredate` varchar(255) NOT NULL,`md5` varchar(255) NOT NULL, PRIMARY KEY  (`id`)) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
    
    $create_table = mysql_query($query)or die (mysql_error());
    }
    
    ///////////////////////////////////////////////////////
    // Status Checker
    ///////////////////////////////////////////////////////
    if ($_GET["status"])
    {
    echo "online";
    exit;
    }
    
    ////////////////////////////////////////////////////////
    // Run some checks on our gameid 
    ////////////////////////////////////////////////////////
    $gameid_safe = mysql_real_escape_string($_GET["gameid"]);
    // Check the gameid is numeric
    // If its not numberic lets exit
    if(!is_numeric($gameid_safe))
    {
     exit; 
    }
    
    ///////////////////////////////////////////////////////
    // Upload new score
    ///////////////////////////////////////////////////////
    // Test for the variables submitted by the player
    // If they exist upload into the database
    
    if ($_GET["playername"] && $_GET["gameid"] && $_GET["score"])
    {
    
    // Strip out | marks submitted in the name or score
    $playername_safe = str_replace("|","_",$_GET["playername"]);
    $playername_safe = mysql_real_escape_string($playername_safe);
    $score_safe = mysql_real_escape_string($_GET["score"]);
    $date = date('M d Y');
        
    // Check the score sent is is numeric
    // If the score is not numberic lets exit
    if(!is_numeric($score_safe))
    {
     exit; 
    }
    
    // this secret key needs to be the same as the secret key in your game.
    $security_md5= md5($_GET["gameid"].$_GET["playername"].$_GET["score"].$secret_key);
    
    // Check for submitted MD5 different then server generated MD5
    if ($security_md5 <>$_GET["code"])
    {
    // Something is wrong -- MD5 security hash is different
    // Could be someone trying to insert bogus score data
    exit;
    }
    // Everything is cool -- Insert the data into the database
    $query = "insert into $tname(gameid,playername,score,scoredate,md5) values ('$gameid_safe','$playername_safe','$score_safe','$date','$security_md5')";
    $insert_the_data = mysql_query($query)or die(mysql_error());
    }
        
    ///////////////////////////////////////////////////////
    // List high score
    ///////////////////////////////////////////////////////
    // Return a list of high scores with "|" as the delimiter
    if ($gameid_safe)
    {
    $query = "select * from $tname where gameid='$gameid_safe' order by score desc limit 10";
    $view_data = mysql_query($query)or die(mysql_error());
    while($row_data = mysql_fetch_array($view_data))
        {
        print($row_data["playername"]);
        print "|";
        print ($row_data["score"]);
        print ("|");
        print($row_data["scoredate"]);
        print("|");
        }
    
    // We limit the score database to hold the number defined in the config script
    // First check to see how many records we have for this game
    
    $query1 ="select * from $tname where gameid = '$gameid_safe'";
    $countresults = mysql_query($query1)or die(mysql_error());
    $countofdeletes = mysql_num_rows($countresults);
    if (mysql_num_rows($countresults)>$score_number)
        {
        $query2 ="SELECT * FROM $tname WHERE gameid = '$gameid_safe' ORDER BY score DESC Limit $score_number,$countofdeletes";
        $Get_data = mysql_query($query2)or die (mysql_error());
        while($row_data = mysql_fetch_array($Get_data))
        {
        $id_delete = $row_data["id"];
        $query3 = "Delete from $tname where id = $id_delete";
        $Delete_data = mysql_query($query3)or die (mysql_error());
        }
        }
    }
    

    ?>[/php]

    fin qui tutto OK, si crea la tabella scores e tutti i campi (id, scores, playername...) vengono creati e aggiornati all'invio dei dati. Il mio problema è però creare una pagina in php, tipo hiscore.php che visualizzi i dati della tabella, allora ho inserito questo:

    [php]
    <?php
    define("DB_HOST", 'localhost');
    define("DB", '+++++++');
    define("DB_USER", '+++++++');
    define("DB_PW", '+++++++');
    mysql_connect(DB_HOST, DB_USER, DB_PW);
    mysql_select_db(DB);
    $query="SELECT * FROM scores ORDER BY score DESC";
    $result= mysql_query($query);
    $numfields = mysql_num_fields($result);

    echo "<table>\n<tr>";
    for ($i=0; $i < $numfields; $i++)
    {
    echo '<th>'.mysql_field_name($result, $i).'</th>';
    }
    echo "</tr>\n";

    while ($row = mysql_fetch_row($result))
    {
    echo '<tr><td>'.implode($row,'</td><td>')."</td></tr>\n";
    }
    echo "</table>\n";
    ?>
    [/php]
    con questo script visualizzo il contenuto della tabella, ma mi fa vedere tutto, compreso l'algoritmo di criptazione, praticamente come si vede qui :

    a me interesserebbe vedere solo playername, score e scoredate, e magari formattarlo in qualche modo.

    Dato che come ho già detto sono sotto lo zero di queste cose, qualcuno può suggerirmi un tutorial, una guida base o qualche informazione su come gestire i dati di una tabella del database per visualizzarli in una pagina web?

    Vi ringrazio anticipatamente.


  • Super User

    Ciao 🙂

    Praticamente il secondo script controlla quanti campi ci sono nella tabella ($numfields) e poi li scorre uno ad uno partendo dal primo e arrivano all'ultimo (for ($i=0; $i < $numfields; $i++))

    In pratica anziché fagli stampare tutto automaticamente, dovresti eliminare quel ciclo for e dirgli i numeri dei campi che vuoi stampare.

    So che non è certamente una spiegazione completa, ma se studi un po' sulla guida ufficiale di php e segui quanto ho detto probabilmente ne vieni a capo.


  • User

    @claudioweb said:

    Ciao 🙂

    Praticamente il secondo script controlla quanti campi ci sono nella tabella ($numfields) e poi li scorre uno ad uno partendo dal primo e arrivano all'ultimo (for ($i=0; $i < $numfields; $i++))

    In pratica anziché fagli stampare tutto automaticamente, dovresti eliminare quel ciclo for e dirgli i numeri dei campi che vuoi stampare.

    So che non è certamente una spiegazione completa, ma se studi un po' sulla guida ufficiale di php e segui quanto ho detto probabilmente ne vieni a capo.
    Grazie per la risposta, è comunque già qualcosa, nel week end provero a seguire i tuoi consigli, vediamo se riesco a impostare qualcosa!!

    Grazie:wink3:


  • User

    ti basta cambiare questa riga:
    [php]
    $query="SELECT * FROM scores ORDER BY score DESC";
    [/php]cambiandola così:
    [php]
    $query="SELECT playername, score, scoredate FROM scores ORDER BY score DESC";
    [/php]Così la query al posto di prendere tutti i campi dalla tabella ( il carattere * ) prende solo "playername, score, scoredate".

    Per la formattazione non so, guarda qualche funzione di manipolazione delle stringhe e aggiungi un po' di HTML...:wink3:

    Tutorial:

    Ti consiglio ancora di fare riferimento alla documentazione di PHP ( php.net ) che è completissima e facile da consultare.

    Per l'SQL, visto che utilizzi MySQL come database ( se guardi le funzoni di PHP legate al database iniziano tutte con "mysql_" ) fai riferimento alla documentazione su mysql.it )

    buon lavoro


  • User

    Grazie infinite, già cos' ho risolto gran parte della tabella che ora è più ordinata e leggibile.

    Grazie ancora.


  • User

    Figurati!!

    Buon lavoro