2016-04-11 13 views
5

Così ho creato un'interfaccia che accetta input da un menu a tendina .. enter image description hereCome utilizzare logicamente PHP per visualizzare tutti i possibili valori di una tabella di database?

visualizza quindi i dati provenienti da tre diverse tabelle di database in una tabella HTML con tutte le voci che corrispondono ai criteri. enter image description here

La tabella è indicata nella parte inferiore dell'immagine precedente.

La mia domanda è: come posso utilizzare PHP, utilizzando loop o altro, per rielaborare il mio codice e creare un'enorme pagina HTML che attraversa ogni singolo evento? AKA ho bisogno di generare 126 tabelle:

enter image description here

Ma io non sono sicuro di come affrontare questo. Il mio pensiero iniziale era quello di usare un ciclo e inserire il codice per generare una sola tabella al suo interno, ma non saprei come fermarne la condizione, né vorrei sapere come scorrere tra le diverse opzioni negli elenchi a discesa. Non sto chiedendo a nessuno di creare il codice per me, ma piuttosto indirizzarmi verso quale logica usare .. dopo di che, probabilmente posso capirlo da solo. Grazie a tutti. :)

Qui di seguito è il mio codice, che uso per generare ogni tavolo, con annotazioni in form commento:

<?php 

error_reporting(E_ALL); 

$dbhost  = "localhost"; //logs into my localhost server 
$dbname  = "sportsDay"; 
$dbuser  = "root"; 
$dbpass  = "..."; 

$year=$_POST['Year']; //gets variables from the drop-downs in the form displayed above 
$gender=$_POST['Gender']; 
$event=$_POST['Event']; 

$result[]=0; 
try 
{ 

    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $conn->exec("SET CHARACTER SET utf8mb4"); 

    $sql = "SELECT Students.lName, Students.fName, Students.house 
    FROM Entries INNER JOIN Events ON Entries.ev1ID = Events.ID 
    JOIN Students ON Students.stID = Entries.stID 
    WHERE (Entries.ev1ID = :event or Entries.ev2ID = :event2) and (Students.year = :year) 
    AND (Students.gender = :gender) 
    ORDER BY Students.house ASC"; 
    //my SQL code that matches up the values from the drop-downs to the values in the database tables 

    $stmt = $conn->prepare($sql); 

    $stmt->bindValue(':event', $event); 
    $stmt->bindValue(':event2', $event); 
    $stmt->bindValue(':year', $year); 
    $stmt->bindValue(':gender', $gender); 

    $stmt->execute(); 
    $result = $stmt->fetchAll(); 
    $count = $stmt->rowCount(); 
} 

catch(PDOException $e) 
{ 
    echo $e->getMessage(); 
} 
    ?> 
    <html> 
    <body> 
    <?php if ($count > 0): ?> //checks to see if there are results. if there are results, it displays them: 
    <table border="1" > 
     <tr> 
      <th>Name</th> 
      <th>House</th> 
      <th>Score</th> 
     </tr> 
     <?php foreach ($result as $row) { 
      ?> 
     <tr> 
      <td><?php echo $row['fName']. ' '.$row['lName'] ?></td> 
      <td><?php echo $row['house'] ?></td> <td></td> 
     </tr> 
     <?php } ?> 
    </table> 
<?php else: echo "No results." ?> //if not, it displays that there are no results. 
<?php endif ?> 
    </body> 
    </html> 
+0

Quindi il messaggio è stato molto da fare, ma sono voi provando a generare molti tavoli contemporaneamente? Questo è quello che ho guadagnato leggendo la parte inferiore? – Jek

+1

@Jek sì, in sostanza sto cercando di generare molte tabelle contemporaneamente. Sono così dispiaciuto che non sia chiaro, modificherò il post per chiarezza. –

+1

@ Jek ha senso ora? –

risposta

1

Dal momento che avete già il vostro codice per generare una tavolo, Lei ha ragione che si può usarlo per generare tutte di loro.

Tutto quello che devi fare è scorrere tutte le possibilità fornite dal modulo.

È necessario disporre di un elenco di opzioni possibili per compilare il modulo HTML, basta utilizzare questi elenchi di opzioni in un ciclo foreach nidificato.

foreach ($event as $e) { 
    foreach ($gender as $g) { 
    foreach ($year as $y) { 
     // Use $e, $g and $y for your query and table construction. 
     $sql = ...; // Query stays the same. 

     $stmt->bindValue(':event', $e); 
     $stmt->bindValue(':event2', $e); 
     $stmt->bindValue(':year', $y); 
     $stmt->bindValue(':gender', $g); 
    } 
    } 
} 

Ecco l'esempio completo in base al codice che hai fornito:

<?php 

error_reporting(E_ALL); 

$dbhost  = "localhost"; //logs into my localhost server 
$dbname  = "sportsDay"; 
$dbuser  = "root"; 
$dbpass  = "..."; 

$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$conn->exec("SET CHARACTER SET utf8mb4"); 

?> 
<html> 
<body> 
<?php 

// Lists of possible DB values 
$event = array("100m", "100m relay", "High Jump", ...); // a list of all events 
$gender = array("F", "M"); // a list of all genders 
$year = array(7, 8, 9, 10, 11, 12); // a list of all classes 

foreach ($event as $e) { 
    foreach ($gender as $g) { 
    foreach ($year as $y) { 

     $result[] = 0; 
     try { 
      $sql = "SELECT Students.lName, Students.fName, Students.house 
      FROM Entries INNER JOIN Events ON Entries.ev1ID = Events.ID 
      JOIN Students ON Students.stID = Entries.stID 
      WHERE (Entries.ev1ID = :event or Entries.ev2ID = :event2) and (Students.year = :year) 
      AND (Students.gender = :gender) 
      ORDER BY Students.house ASC"; 

      $stmt = $conn->prepare($sql); 

      $stmt->bindValue(':event', $e); 
      $stmt->bindValue(':event2', $e); 
      $stmt->bindValue(':year', $y); 
      $stmt->bindValue(':gender', $g); 

      $stmt->execute(); 
      $result = $stmt->fetchAll(); 
      $count = $stmt->rowCount(); 
     } 
     catch (PDOException $e) { 
      echo $e->getMessage(); 
     } 

    if ($count > 0) { 
?> 
    <table border="1" > 
     <tr> 
      <th>Name</th> 
      <th>House</th> 
      <th>Score</th> 
     </tr> 
     <?php foreach ($result as $row) { 
      ?> 
     <tr> 
      <td><?php echo $row['fName']. ' '.$row['lName'] ?></td> 
      <td><?php echo $row['house'] ?></td> <td></td> 
     </tr> 
     <?php } ?> 
    </table> 

<?php 
     } 
     else { 
     echo "No results for $e ($g, $y)."; 
     } 
    } 
    } 
} 
?> 
</body> 
</html> 
+1

Ciao Paul, capisco il ragionamento dietro questo metodo foreach(). Tuttavia sono molto confuso su come implementarlo nell'azione del modulo: "$ anno = $ _ POST ['Anno']; $ genere = $ _ POST ['Sesso']; $ evento = $ _ POST ['Evento ']; "Devo cambiare questa parte, giusto? –

+0

Non hai più bisogno del modulo poiché tutte le possibilità (tabelle) verranno stampate. Potresti semplicemente usare le variabili '$ e $ g e $ y' nella tua query del database. Vedi la risposta aggiornata. – Paul

+1

Umm .. http://pastebin.com/jWyMjJku piace questo? Sono molto confuso, mi dispiace ... sembra che manchi qualcosa di importante ... –

0

Ho ricreato la struttura db. Utilizzando un join di sinistra, sono stato in grado di recuperare tutti i dati necessari ordinati per ID evento.

mio database ricreazione:

tavolo Studenti tavolo

+------+---------+-----------+-------+ 
| stID | fName | lName  | house | 
+------+---------+-----------+-------+ 
| 1 | Nadir | Roman  | east | 
| 2 | Jesus | Lopez  | west | 
| 3 | Ioannis | Chalkadis | west | 
| 4 | Adry | Pepes  | east | 
| 5 | David | Caretas | west | 
+------+---------+-----------+-------+ 

Eventi tavolo

+----+-----------+---------------+ 
| ID | name  | location  | 
+----+-----------+---------------+ 
| 1 | 100m  | Track   | 
| 2 | 400m  | Track   | 
| 3 | High Jump | High Jump Pit | 
+----+-----------+---------------+ 

punteggi

+------+-------+-------+ 
| stID | ev1ID | ev2ID | 
+------+-------+-------+ 
| 1 |  1 |  2 | 
| 2 |  2 |  3 | 
| 3 |  1 |  3 | 
| 4 |  1 |  2 | 
| 5 |  1 |  3 | 
+------+-------+-------+ 

la query:

mysql> SELECT Events.ID, Events.name, location, Scores.stID, fName, lName, house FROM Scores LEFT JOIN (Students, Events) ON (Students.stID = Scores.stID AND (Events.ID = Scores.ev1ID OR Events.ID = Scores.ev2ID)) ORDER BY ID; 

e l'uscita è:

+------+-----------+---------------+------+---------+-----------+-------+ 
| ID | name  | location  | stID | fName | lName  | house | 
+------+-----------+---------------+------+---------+-----------+-------+ 
| 1 | 100m  | Track   | 1 | Nadir | Roman  | east | 
| 1 | 100m  | Track   | 5 | David | Caretas | west | 
| 1 | 100m  | Track   | 4 | Adry | Pepes  | east | 
| 1 | 100m  | Track   | 3 | Ioannis | Chalkadis | west | 
| 2 | 400m  | Track   | 2 | Jesus | Lopez  | west | 
| 2 | 400m  | Track   | 1 | Nadir | Roman  | east | 
| 2 | 400m  | Track   | 4 | Adry | Pepes  | east | 
| 3 | High Jump | High Jump Pit | 2 | Jesus | Lopez  | west | 
| 3 | High Jump | High Jump Pit | 5 | David | Caretas | west | 
| 3 | High Jump | High Jump Pit | 3 | Ioannis | Chalkadis | west | 
+------+-----------+---------------+------+---------+-----------+-------+ 

È possibile dividere questo output in diverse matrici, 1 per evento:

$result = $stmt->fetchAll(); 
$mappedEvents = []; 

array_map(function($entry) 
{ 
    if(!isset($mappedEvents[$entry['ID']])) 
    { 
     $mappedEvents[$entry['ID']] = []; 
    } 
    $mappedEvents[$entry['ID'][] = $entry; 
}, $result); 

foreach($mappedEvents as $eventID => $data) 
{ 
     // $eventID = event ID 
     // $data = Array with all info about the event (students, location, etc..) 
} 
+1

ciao bene signore. I punteggi non sono una tabella nel database :) è semplicemente una parte esterna della tabella, perché il sistema che sto creando ha lo scopo di creare pagine che possono essere stampate in modo che le pagine possano essere scritte a mano, ovvero le la colonna vuota del tavolo è vuota e può essere riempita di persona. Inoltre, posso chiedere una spiegazione ulteriore della tua risposta? Non capisco come risponde alla mia domanda perché sono molto inesperto in PHP e temo di aver frainteso la tua risposta. grazie nadir :) –

+0

Forse ho capito male la tua domanda. Stai provando a creare una pagina html che elenchi una tabella per ciascun evento e su ogni tabella dovresti visualizzare le informazioni sugli studenti che partecipano a loro, giusto? – Nadir

+0

sì. :) ma ho bisogno di una tabella separata per ogni evento, sembra che il tuo output sia un unico tavolo? –