[php] Problema con inner join

Kiko74b

Nuovo Utente
26 Giu 2022
19
2
3
Salve vorrei chiarimenti su questa cosa:
Ho due tabelle cosi composte :
tabella categorie
-id (chiave primaria)
-name
-crteated

tabella prodotti
-id ( chiave primaria , unica)
- nome_prodotto
- quantita
- descrizione
-categoria_id ( chiave unica )
-created
-modified

Il mio intento è quello di fare una query che mi visualizzi tutti i prodotti ed estrapolare il nome del prodotto considerando che categoria_id della tabella prodotti è uguale all' id della tabella categorie
Ho fatto in questo modo:
prima creo due classi per le operazioni da eseguire sul database mysql
il file categorie.class.php è cosi definito
PHP:
<?php
class Categorie{
  
    // database connection and table name
    private $conn;
    private $table_name = "categorie";
  
    // object properties
    public $id;
    public $name;
  
    public function __construct($db){
        $this->conn = $db;
    }
    
    //used to create categorie
    function create(){
  
        //write query
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                   name=:name, created=:created";
  
        $stmt = $this->conn->prepare($query);
  
        // posted values
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->created=htmlspecialchars(strip_tags($this->created));
        
  
        // to get time-stamp for 'PIANO_TERAPEUTICO' field
        $this->created = date('d-m-Y');
  
        // bind values 
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":created", $this->created);
        
        //$stmt->bindParam(":created", $this->timestamp);
  
        if($stmt->execute()){
            return true;
        }else{
            return false;
        }
  
    }

  
    // used by select drop-down list
    function read(){
        //select all data
        $query = "SELECT
                    id, name
                FROM
                    " . $this->table_name . "
                ORDER BY
                    name";  
  
        $stmt = $this->conn->prepare( $query );
        $stmt->execute();
  
        return $stmt;
    }
    // used to read category name by its ID
    function readName(){
          
        $query = "SELECT name FROM " . $this->table_name . " WHERE id = ? limit 0,1";
      
        $stmt = $this->conn->prepare( $query );
        $stmt->bindParam(1, $this->id);
        $stmt->execute();
      
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
          
        $this->name = $row['name'];
    }
  
}
?>

mentre il file prodotti.class.php
PHP:
<?php
class Categorie{
  
    // database connection and table name
    private $conn;
    private $table_name = "categorie";
  
    // object properties
    public $id;
    public $name;
  
    public function __construct($db){
        $this->conn = $db;
    }
    
    //used to create categorie
    function create(){
  
        //write query
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                   name=:name, created=:created";
  
        $stmt = $this->conn->prepare($query);
  
        // posted values
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->created=htmlspecialchars(strip_tags($this->created));
        
  
        // to get time-stamp for 'PIANO_TERAPEUTICO' field
        $this->created = date('d-m-Y');
  
        // bind values 
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":created", $this->created);
        
        //$stmt->bindParam(":created", $this->timestamp);
  
        if($stmt->execute()){
            return true;
        }else{
            return false;
        }
  
    }

  
    // used by select drop-down list
    function read(){
        //select all data
        $query = "SELECT
                    id, name
                FROM
                    " . $this->table_name . "
                ORDER BY
                    name";  
  
        $stmt = $this->conn->prepare( $query );
        $stmt->execute();
  
        return $stmt;
    }
    // used to read category name by its ID
    function readName(){
          
        $query = "SELECT name FROM " . $this->table_name . " WHERE id = ? limit 0,1";
      
        $stmt = $this->conn->prepare( $query );
        $stmt->bindParam(1, $this->id);
        $stmt->execute();
      
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
          
        $this->name = $row['name'];
    }
  
}
?>
la pagina prodotti.php che visualizza tutti i prodotti è cosi definito:
PHP:
<?php
// page given in URL parameter, default page is one
$page = isset($_GET['page']) ? $_GET['page'] : 1;
  
// set number of records per page
$records_per_page = 10;
  
// calculate for the query LIMIT clause
$from_record_num = ($records_per_page * $page) - $records_per_page;
//includo oggettoi database , categorie , prodotti
include_once 'config/db_1.php';
include_once 'inc/prodotti.class.php';
include_once 'inc/categorie.class.php';
?>
<html>
<head>
<title>GESTIONE DIABETICI</title>
<style>
body{width:100%;font-family:arial;letter-spacing:1px;line-height:20px;}
.tbl-qa{width: 100%;font-size:0.9em;background-color: #f5f5f5;}
.tbl-qa th.table-header {padding: 5px;text-align: left;padding:10px;}
.tbl-qa .table-row td {padding:10px;background-color: #FDFDFD;vertical-align:top;}
.button_link {color:#FFF;text-decoration:none; background-color:#428a8e;padding:10px;}
</style>
</head>
<body>
<?php
$database = new Database();
$db = $database->getConnection();
    //create object 
$prodotti = new Prodotti($db);
$categorie = new Categorie($db);
    // query to read prodotti
$stmt = $prodotti->readAll($from_record_num, $records_per_page);
$num = $stmt->rowCount();

$name = $categorie->readName($name); 
    //query to read categorie name SELECT book.title, author, description, date, filename, user.name, email
  //FROM book INNER JOIN user ON book.user_id = user.id";
//$categoria_id = $categorie->nome_categoria();
//$categoria_id = $db->prepare("SELECT categorie.id, name, prodotti.categoria_id FROM categorie INNER JOIN prodotti ON categorie.id = prodotti.categorie_id");
//$categoria_id->execute();
    
?>
<div style="text-align:right;margin:20px 0px;">
    <a href="clienti.php" class="button_link"><img src="images/icon/add.png" title="Lista Cliente" style="vertical-align:bottom;" /> Clienti</a>
    <a href="prodotti.php" class="button_link"><img src="images/icon/add.png" title="Lista Prodotto" style="vertical-align:bottom;" /> Prodotti</a>
    <a href="erogazioni.php" class="button_link"><img src="images/icon/add.png" title="Lista Erogazione" style="vertical-align:bottom;" /> Erogazioni</a>
    <a href="categorie.php" class="button_link"><img src="images/icon/add.png" title="Lista Categorie" style="vertical-align: bottom;" />Categorie</a></div>
<table class="tbl-qa">
  <thead>
    <tr>
      <th class="table-header" width="20%">Nome Prodotto: </th>
      <th class="table-header" width="20%">Quantita: </th>
      <th class="table-header" width="15%">Descrizione: </th>
      <th class="table-header" width="5%">Categoria: </th>
      <th class="table-header" width="15%">Creato il: </th>
      <th class="table-header" width="5%">Azioni: </th>
    </tr>
  </thead>
  <tbody id="table-body">
    <?php
    // display the products if there are any
if($num>0){
    /* if(!empty($result)) { 
        foreach($result as $row) { 
    */
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
  
            extract($row);
    ?>
      <tr class="table-row">
        <td><?php echo $nome_prodotto; ?></td>
        <td><?php echo $quantita; ?></td>
        <td><?php echo $descrizione; ?></td>
        <td><?php echo $name; ?></td>
        <td><?php echo $created; ?></td>
        <td><a class="ajax-action-links" href='aggiorna_cliente.php?id=<?php echo $row['id']; ?>'><img src="images/icon/edit.png" title="Edit" /></a> <a class="ajax-action-links" href='cancella_cliente.php?id=<?php echo $row['id']; ?>'><img src="images/icon/delete.png" title="Delete" /></a></td>
        <?php
        }
    }
    ?>
      </tr>
  </tbody>
</table>
    </div>
    <!-- /container -->
  <div class="container">
  
        <?php
        // show page header
        echo "<div class='page-header'>
                <h1>{$page_title}</h1>
            </div>";
        ?>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>

   
<!-- bootbox library last version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.5.2/bootbox.min.js" integrity="sha512-RdSPYh1WA6BF0RhpisYJVYkOyTzK4HwofJ3Q7ivt/jkpW6Vc8AurL1R+4AUcvn9IwEKAPm/fk7qFZW3OuiUDeg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="/js/script.js"></script> 
</body>
</body>
</html>
Quando visualizzo la pagina prodotti sul campo categoria_id non riesco ad ottenere il nome della categoria associata. Qualche consiglio per effettuare questa operazione?
Si possono creare più oggetti nella pagina prodotti? cosi come ho postato...
inoltre è giusto chiamare la funzione readName per leggere il nome della categoria riferito a categoria id ?
inoltre vorrei sapere se è giusto creare delle foreign key nel mysql che mettono in relazione id con categoria_id
 

marino51

Utente Attivo
28 Feb 2013
3.204
207
63
Lombardia
scrivo una query che dovrebbe funzionare per estrarre i valori delle due tabelle,
confesso non ho guardato il codice e ho capito anche poco ciò che hai scritto
spero che la query ti aiuti

SQL:
select
  p.id
, p.nome_prodotto
, p.quantita
, p.descrizione
, p.categoria_id
, p.created
, p.modified
, c.id
, c.name as NOME -- attenzione name può essere una parola riservata
, c.created
from prodotti p
left join categorie c
on p.categoria_id = c.id
where c.id = 1234567890
order by p.nome_prodotto
 

Kiko74b

Nuovo Utente
26 Giu 2022
19
2
3
Ho provato anche questa soluzione per estrarre il nome categoria derivante dalla relazione c.id =p.categoria_id La funzione è implementata come metodo nella classe action ma non mi da alcun risultato...
PHP:
function name(){
$query = "SELECT name  FROM categorie INNER JOIN prodotti ON prodotti.categoria_id = categorie.id";
    $stmt = $this->conn->prepare($query);
    $stmt->execute();
    $row = $stmt->fetchall(PDO::FETCH_ASSOC);
    $this->name = $row['name'];
 

marino51

Utente Attivo
28 Feb 2013
3.204
207
63
Lombardia
ho scritto che name può essere una parola riservata che da errore se usata nelle query

anche la query che hai scritto per estrarre la colonna "name" ha poco senso, fai prima a scrivere

select * from categorie

che ti viene meglio
 

Kiko74b

Nuovo Utente
26 Giu 2022
19
2
3
ho scritto che name può essere una parola riservata che da errore se usata nelle query

anche la query che hai scritto per estrarre la colonna "name" ha poco senso, fai prima a scrivere

select * from categorie

che ti viene meglio
ok grazie per il consiglio quindi cambio la parola name con nome_categoria sia in mysql che nel codice php e seleziono tutti i record della tabella categorie. Sto cercando di capire come funziona pdo crud ho ordinato anche un libro che dovrebbe arrivarmi a breve su php 8 basato sulla programmazione ad oggetti.
 
Discussioni simili
Autore Titolo Forum Risposte Data
K [PHP] Problema con variabili concatenate. PHP 1
T ALTRO PROBLEMA CON ARRAY PHP PHP 1
Z Problema di sincronizzazione PAYPAL con PHP PHP 1
M Problema con php per calcolo costo percentuale PHP 7
L [PHP] Problema con Telegram PHP 1
K Help: problema con uno script di booking in php! PHP 0
N [Apache] problema con estensione php Apache 0
C [PHP] Problema con download file PHP 0
M [PHP] Problema con preg_match PHP 1
gandalf1959 [PHP] problema con l'utilizzo di Header PHP 3
M [PHP] Problema con query select PHP 2
S [PHP] Problema con istruzione "use" PHP 23
Cosina [PHP] fwrite problema con le parole accentate PHP 9
F [PHP] Problema con number_format PHP 3
C Apache Cordova problema con php Programmazione 1
T PHP+MYSQL: problema con quelle maledette lettere accentate... PHP 5
F [PHP] Problema con array multidimensionale PHP 4
F Problema con pagine login in PHP PHP 2
A [PHP] Problema invio mail con funzione mail() PHP 3
gandalf1959 problema con la codifica caratteri accentati e speciali tra php e mysql PHP 3
webmachine [PHP][MYSQL] Problema con le SELECT PHP 5
alessandra86 [PHP] Popolamento database con form ricorsivi - problema array (foreach ) PHP 5
C [PHP] problema con un esercizio PHP 2
P [PHP] Problema con accenti ed apostrofi PHP 0
R [PHP] Problema stampa array bidimensionali con formula $html.=<<<myHtml... PHP 2
M [PHP] problema con preg_match PHP 11
L [PHP] problema con upload e javascript (upload multiplo) Javascript 2
D [PHP] problema con xml PHP 13
T4MAR4 [PHP] Problema ricerca con apostrofo PHP 2
xone Problema FPDF con pagina dinamica PHP PHP 1
A Problema con getCurrentPosition e passaggio variabili da javascript a PHP Javascript 3
SebaGravi [PHP] problema url semantici con .htaccess PHP 3
L [PHP] problema parsing con comando file get contents PHP 7
L Problema con recupero dati in PHP cURL e JAVA con server PHP 1
zammaeng [PHP] Problema form con lista PHP 8
M [PHP] Problema con algoritmo struttura iterativa PHP 2
D Problema con query in php PHP 5
S Problema con script php-javascript PHP 2
M [PHP] Problema con query PHP 17
C [PHP] Problema con creazione csv PHP 3
B sitoweb responsivo problema con include php HTML e CSS 1
neo996sps PHP/MySQL - Problema con generazione array PHP 14
P problema con codice php... PHP 7
C Problema con html e php :D PHP 1
E php problema incremento e decremento di 2 variabili con click da pulsante PHP 0
G Problema con codice php PHP 1
L xml e php. Problema con i nodi PHP 4
P Problema con file di registrazione in php, non funziona e dà continui errori PHP 0
R problema con pagine php apache su centos 5.3 Apache 1
V problema con mail e php PHP 6

Discussioni simili