IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PHP & Base de données Discussion :

Requête SQL sous PHP


Sujet :

PHP & Base de données

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut Requête SQL sous PHP
    Bonjour,

    Je suis désolé mais ce meme message à été déplacé dans cette partie du forum mais je n'arrive pas a y répondre pour plus de détail. Je dois souligner que je suis vraiment néophite dans la gestion de requête SQL et de PHP.

    Je dois creer une requete sql dans un fichier PHP afin de faire un rapport.
    J'ai trois tables:

    table glpi.computers
    -id
    -computertypes_id
    -locations_id
    - ...

    table glpi.computertypes
    -id
    -name
    -...

    table glpi.locations
    -id
    -completename
    -...

    je souahaite faire un "tri" du nombre de 'glpi.computer' par "glpi.computertypes" -> name
    par "glpi.locations" -> completename

    par exemple:
    locations - type - nombre
    paris - pc - 25
    paris - laptop - 12
    marseille - pc -10

    Voici mon fichier PHP après travail sur la partie Nombre de PC par lieu j'ai besoins d'aide pour le modifier afin de l'avoir par type :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    <?php
    $USEDBREPLICATE= 1;
    $DBCONNECION_REQUIRED= 0;
     
    define('GLPI_ROOT', '../../../..');
    include(GLPI_ROOT."/inc/includes.php");
     
    $report= new PluginReportsAutoReport();
     
     
    $report->setColumns(array(new PluginReportsColumn('entity', $LANG['entity'][0]),
                              new PluginReportsColumn('location', $LANG['common'][15]),
                              new PluginReportsColumnInteger('computernumber',$LANG['Menu'][0])));
     
    $query = "SELECT a.`entity`, a.`location`, b.`computernumber`, a.`id`
                                      FROM (SELECT `glpi_entities`.`completename` AS entity,
                                                   `glpi_locations`.`completename` AS location,
                                                   `glpi_locations`.`id` AS id
                                            FROM `glpi_locations`
                                            LEFT JOIN `glpi_entities`
                                              ON (`glpi_locations`.`entities_id`=`glpi_entities`.`id`) ".
                                            getEntitiesRestrictRequest(" WHERE ", "glpi_locations").") a
                                      LEFT OUTER JOIN (SELECT count(*) AS computernumber,
                                                              `glpi_computers`.`locations_id` AS id
                                                       FROM `glpi_computers`
                                                       WHERE is_deleted=0 AND is_template=0
                                                       ".getEntitiesRestrictRequest(" AND ", "glpi_computers")."
                                                       GROUP BY `glpi_computers`.`locations_id`) b
                                           ON (a.id = b.id)";
     
    $report->setGroupBy("entity");					  
    $report->setSqlRequest($query);			  
    $report->execute();						  
     
    ?>

  2. #2
    Membre Expert
    Homme Profil pro
    Inscrit en
    Septembre 2009
    Messages
    875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Septembre 2009
    Messages : 875
    Par défaut
    je ne connais pas PluginReportsAutoReport, mais il suffit peut etre de faire un ORDER BY b.`entity` dans la requete.

    sinon, si votre requête est trop complexe a modifier, il reste toujours la solution un peu crado de faire le tri en php sur les résultats de la requete

  3. #3
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Bonjour,

    je reviens vers vous car la demande à changée et je ne m'y retrouve plus en SQL ...

    Citation Envoyé par gototog Voir le message
    je ne connais pas PluginReportsAutoReport, mais il suffit peut etre de faire un ORDER BY b.`entity` dans la requete.
    j'ai effectuer les modifications avec le GROUPby

    Citation Envoyé par gototog Voir le message
    sinon, si votre requête est trop complexe a modifier, il reste toujours la solution un peu crado de faire le tri en php sur les résultats de la requete
    je m'y connais autant en PHP qu'en SQL se qui veut dire rien

    Je récapitule, j'ai maintenant 4 tables :

    table glpi_computers
    -id
    -computertypes_id
    -locations_id
    -groups_id
    - ...

    table glpi_computertypes
    -id
    -name
    -...

    table glpi_locations
    -id
    -completename
    -...

    table glpi_groups
    -id
    -name
    -groups_id
    -...

    il me faudrais quelque chose comme :

    GROUPE - LIEU - TYPE - NOMBRE

    groupe a lieu a type a 1
    groupe a lieu a type b 2
    groupe a lieu b type a 3
    groupe a lieu b type b 4
    groupe b lieu a type a 5
    ...

    soit :
    GROUPE
    glpi_groups.name
    - LIEU
    glpi_location.completename
    TYPE
    glpi_computertypes.name
    - NOMBRE
    x

    j'aimerais que l'on m'aide a monter la requête pour le faire en mettant dedans :

    - Groupe ne comprendras pas 'groupe c' et 'groupe d'
    - Lieu ne comprendras pas 'lieu c' et 'lieu d'
    - type ne comprendras pas 'type c' et 'type d'

    Je suis complètement perdu

    J'arrive juste a comprendre ma précédente requête mais celle la je ne visualise pas grand chose

  4. #4
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Bonjour j'ai avancé sur la requête SQL qui me donne le résultat suivant

    groupe a lieu a type a
    groupe a lieu a type b
    groupe a lieu b type a
    groupe a lieu b type b
    groupe b lieu a type a

    avec :

    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    SELECT glpi_groups.name, glpi_locations.completename, glpi_computertypes.name
    FROM glpi_groups, glpi_locations, glpi_computertypes
    WHERE glpi_groups.name != "Informatique" AND glpi_groups.name != "Infrastructure" AND glpi_groups.name != "Logiciel"
    AND glpi_computertypes.name != "Serveur" AND glpi_computertypes.name != "Virtual machine"
    AND glpi_computertypes.name != "Other" AND glpi_computertypes.name != "Unknown"
    ORDER BY glpi_groups.name

    il me reste plus qu'a utiliser un COUNT pour compter le nombre de pc par type et a lier celui ci pourrait-on m'aider sur ce point ?

  5. #5
    Membre Expert
    Avatar de Dendrite
    Femme Profil pro
    Développeuse informatique
    Inscrit en
    Juin 2008
    Messages
    2 129
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 59
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeuse informatique
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Juin 2008
    Messages : 2 129
    Billets dans le blog
    8
    Par défaut
    Ah ben ça, typiquement en mysql, c'est group by...

    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    SELECT   count(id) as nb,species
    FROM     menagerie
    GROUP BY species
    PDO, une soupe et au lit !
    Partir de la fin est un bon moyen de retrouver son chemin. Bibi - 2020

  6. #6
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    bonjour,

    Merci de ta réponse Dendrite, j'ai adapté ta requête dans la mienne et cela donne :

    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    SELECT glpi_groups.name AS groupe, glpi_locations.completename AS lieu, glpi_computertypes.name AS type, COUNT(glpi_computers.id) AS nombre
     
    FROM glpi_groups, glpi_locations, glpi_computertypes, glpi_computers
     
    WHERE glpi_groups.name != "Informatique" AND glpi_groups.name != "Infrastructure" AND glpi_groups.name != "Logiciel"
    AND glpi_computertypes.name != "Serveur" AND glpi_computertypes.name != "Virtual machine"
    AND glpi_computertypes.name != "Other" AND glpi_computertypes.name != "Unknown"
     
    AND (glpi_computers.computertypes_id = glpi_computertypes.id && glpi_computers.locations_id = glpi_locations.id && glpi_computers.groups_id = glpi_groups.id)
     
    GROUP BY glpi_computers.computertypes_id
     
    ORDER BY glpi_groups.name, glpi_locations.completename

    Avec cette nouvelle version de la requête j'ai un problème, c'est le

    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    GROUP BY glpi_computers.computertypes_id

    Pourquoi ? Ben parce que en fait il me regroupe les entrées de types d'ordinateur et pour ma part je ne le souhaite pas car je dois avoir quelque chose du genre :

    GROUPE - LIEU - TYPE - NOMBRE

    groupe a lieu a type a 1
    groupe a lieu a type b 2
    groupe a lieu b type a 3
    groupe a lieu b type b 4
    groupe b lieu a type a 5

    Alors que j'ai avec cette requête :


    GROUPE - LIEU - TYPE - NOMBRE

    groupe a lieu a type a 1
    groupe a lieu a type b 2

    Comment puis-je contourner cette difficultée ?

  7. #7
    Membre expérimenté
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2004
    Messages
    144
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : Vatican

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Mai 2004
    Messages : 144
    Par défaut
    Tu devrais optimiser ta requête avec des join, le mieux c'est left join.

    Mais pour ton problème de regroupement tu devrais ajouter le nom de chaque colonne sur la quelle tu veux faire un regroupement, dans ton cas :

    group by a,b,c

    voilà à quoi cela devrais ressembler, essaies et fais signe
    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    SELECT glpi_groups.name AS groupe, glpi_locations.completename AS lieu, glpi_computertypes.name AS type, COUNT(glpi_computers.id) AS nombre
     
    FROM glpi_computers left join glpi_groups ON (glpi_computers.groups_id = glpi_groups.id) LEFT JOIN glpi_locations ON (glpi_computers.locations_id = glpi_locations.id) LEFT JOIN  glpi_computertypes ON (glpi_computers.computertypes_id = glpi_computertypes.id) 
     
    WHERE glpi_groups.name != "Informatique" AND glpi_groups.name != "Infrastructure" AND glpi_groups.name != "Logiciel"
    AND glpi_computertypes.name != "Serveur" AND glpi_computertypes.name != "Virtual machine"
    AND glpi_computertypes.name != "Other" AND glpi_computertypes.name != "Unknown"
     
     
     
    GROUP BY glpi_computers.groups_id,glpi_computers.locations_id,glpi_computers.computertypes_id
     
    ORDER BY glpi_groups.name, glpi_locations.completename

  8. #8
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Merci effectivement cela fonctionne très bien, merci de ses précisions

    J'ai juste une dernière demande par rapport à cette requête, est il possible de faire :

    GROUPE - LIEU - TYPE A - TYPE B - TYPE C

    groupe a lieu a N1 N2 N3
    groupe a lieu b N4 N5 N6
    groupe b lieu a N7 N8 N9

    Nx étant le nombre de pc du type A,B ou C

  9. #9
    Membre expérimenté
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2004
    Messages
    144
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : Vatican

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Mai 2004
    Messages : 144
    Par défaut
    Bien sur c'est possible voilà à quoi ça ressemble :
    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     
    SELECT glpi_groups.name AS groupe, glpi_locations.completename AS lieu, glpi_computertypes.name AS type, 
    COUNT((CASE WHEN glpi_computers.computertypes_id='type1' THEN glpi_computers.id ELSE NULL END)) AS 'type1',
    COUNT((CASE WHEN glpi_computers.computertypes_id='type2' THEN glpi_computers.id ELSE NULL END)) AS 'type2',
    COUNT((CASE WHEN glpi_computers.computertypes_id='type3' THEN glpi_computers.id ELSE NULL END)) AS 'type3'
     
    FROM glpi_computers left join glpi_groups ON (glpi_computers.groups_id = glpi_groups.id) LEFT JOIN glpi_locations ON (glpi_computers.locations_id = glpi_locations.id) LEFT JOIN  glpi_computertypes ON (glpi_computers.computertypes_id = glpi_computertypes.id) 
     
    WHERE glpi_groups.name != "Informatique" AND glpi_groups.name != "Infrastructure" AND glpi_groups.name != "Logiciel"
    AND glpi_computertypes.name != "Serveur" AND glpi_computertypes.name != "Virtual machine"
    AND glpi_computertypes.name != "Other" AND glpi_computertypes.name != "Unknown"
     
     
     
    GROUP BY glpi_computers.groups_id,glpi_computers.locations_id,glpi_computers.computertypes_id
     
    ORDER BY glpi_groups.name, glpi_locations.completename

    remplace le type1 etc par tes valeurs. Cette requête prend en compte trois type1 tu peux ajouter autant de lignes count :
    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    COUNT((CASE WHEN glpi_computers.computertypes_id='typeX' THEN glpi_computers.id ELSE NULL END)) AS 'typeX',

    mais le problème est que tu est obligé d’éditer cette requête à chaque modification dans la table des types en l’occurrence un ajout de type. dans le cas où on travaille ce genre de requêtes avec de tables qui sont quotidiennement mis à jour avec des ajout il faudrait penser à des constructeurs de requêtes sql via php.
    en effet tu peux parcourir ta tables de types et construire la clause sql dynamiquement puis l'exécuter :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
     
    $types_query= mysql_query("select distinct glpi_computertypes.id,glpi_computertypes.name from glpi_computertypes");
    $nb_lignes=mysql_num_rows($types_query);
    $sql_string="";
    for ($h = 0; $h < $nb_lignes; ++$h){
    $fetch_types_query=mysql_fetch_row($types_query);
    $type_id=$fetch_types_query[0];
    $type_label=$fetch_types_query[1];
     
    if ($h<($nb_lignes-1)){
    $sql_string.="COUNT((CASE WHEN glpi_computers.computertypes_id='type_id' THEN glpi_computers.id ELSE NULL END)) AS 'type_label',";
    }elseif($h==($nb_lignes-1)){
    	$sql_string.="COUNT((CASE WHEN glpi_computers.computertypes_id='type_id' THEN glpi_computers.id ELSE NULL END)) AS 'type_label'";
    }
    }
     
    $glbal_sql_string="SELECT glpi_groups.name AS groupe, glpi_locations.completename AS lieu,
    $sql_string 
    FROM glpi_computers left join glpi_groups ON (glpi_computers.groups_id = glpi_groups.id) LEFT JOIN glpi_locations ON (glpi_computers.locations_id = glpi_locations.id) LEFT JOIN  glpi_computertypes ON (glpi_computers.computertypes_id = glpi_computertypes.id) 
     
    WHERE glpi_groups.name != "Informatique" AND glpi_groups.name != "Infrastructure" AND glpi_groups.name != "Logiciel"
    AND glpi_computertypes.name != "Serveur" AND glpi_computertypes.name != "Virtual machine"
    AND glpi_computertypes.name != "Other" AND glpi_computertypes.name != "Unknown"
     
     
     
    GROUP BY glpi_computers.groups_id,glpi_computers.locations_id
     
    ORDER BY glpi_groups.name, glpi_locations.completename
    ";
     
    // et là tu as ta  requête globale que tu pouras executer

  10. #10
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Merci mandrake_of_mandregas,

    J'ai compris l utilisation du :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    COUNT((CASE WHEN glpi_computers.computertypes_id='typeX' THEN glpi_computers.id ELSE NULL END)) AS 'typeX',
    Pour le reste "je comprend pas le chinois" nan sans rire mon niveau en PhP est assez médiocre. Mais pour mon utilisation je n'ai pas besoins de creer les colonnes en fonction d'une table car j'ai besoins que de certain type donc que ce soit écrit en "dur" ne dérangeras personne.

  11. #11
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Voici donc ma nouvelle requête SQL :

    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    SELECT glpi_groups.name AS groupe, glpi_locations.completename AS lieu, 
    COUNT((CASE WHEN glpi_computers.computertypes_id='1' THEN glpi_computers.id ELSE NULL END)) AS 'desktop',
    COUNT((CASE WHEN glpi_computers.computertypes_id='14' THEN glpi_computers.id ELSE NULL END)) AS 'laptop',
    COUNT((CASE WHEN glpi_computers.computertypes_id='2' THEN glpi_computers.id ELSE NULL END)) AS 'portable'
     
    FROM glpi_computers 
     
    LEFT JOIN glpi_groups ON (glpi_computers.groups_id = glpi_groups.id) 
    LEFT JOIN glpi_locations ON (glpi_computers.locations_id = glpi_locations.id) 
    LEFT JOIN  glpi_computertypes ON (glpi_computers.computertypes_id = glpi_computertypes.id) 
     
    WHERE glpi_groups.name != "Informatique" AND glpi_groups.name != "Infrastructure" AND glpi_groups.name != "Logiciel"
    AND glpi_computertypes.name != "Serveur" AND glpi_computertypes.name != "Virtual machine"
    AND glpi_computertypes.name != "Other" AND glpi_computertypes.name != "Unknown"
     
    AND glpi_computers.states_id = '1' 
     
    GROUP BY glpi_computers.groups_id,glpi_computers.locations_id
     
    ORDER BY glpi_groups.name, glpi_locations.completename

    Cette requête me renvoi bien le résultat attendu avec MySQK Workbench.
    J'essaye d'integrer cela dans mon fichier PHP comme ce qui suit :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    <?php
    $USEDBREPLICATE= 1;
    $DBCONNECION_REQUIRED= 0;
     
    define('GLPI_ROOT', '../../../..');
    include(GLPI_ROOT."/inc/includes.php");
     
    $report= new PluginReportsAutoReport();
     
     
    $report->setColumns(array(new PluginReportsColumn('groupe', 'groupe'),
                              new PluginReportsColumn('lieu', 'lieu'),
    			  new PluginReportsColumn('desktop', 'desktop'),
    			  new PluginReportsColumn('laptop', 'laptop'),
    			  new PluginReportsColumn('portable', 'portable')));
     
    $query = "SELECT `glpi_groups`.`name` AS groupe, `glpi_locations`.`completename` AS lieu, 
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`='1' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'desktop',
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`='14' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'laptop',
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`='2' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'portable'
     
    FROM `glpi_computers` 
    LEFT JOIN `glpi_groups` ON (`glpi_computers`.`groups_id` = `glpi_groups`.`id`) 
    LEFT JOIN `glpi_locations` ON (`glpi_computers`.`locations_id` = `glpi_locations`.`id`) 
    LEFT JOIN `glpi_computertypes` ON (`glpi_computers`.`computertypes_id` = `glpi_computertypes`.`id`) 
     
    WHERE `glpi_groups`.`name` != 'Informatique' AND `glpi_groups`.`name` != 'Infrastructure' 
    AND `glpi_groups`.`name` != 'Logiciel'
    AND `glpi_computertypes`.`name` != 'Serveur' AND `glpi_computertypes`.`name` != 'Virtual machine'
    AND `glpi_computertypes`.`name` != 'Other' AND `glpi_computertypes`.`name` != 'Unknown'
     
    AND `glpi_computers`.`states_id` = '1' 
     
    GROUP BY `glpi_computers`.`groups_id`, `glpi_computers`.`locations_id`
     
    ORDER BY `glpi_groups`.`name`, `glpi_locations.completename`";
     
    $report->setSqlRequest($query);			  
    $report->execute();						  
     
    ?>
    Le problème est que lorsque je lance mon rapport il me dis qu'il ne trouve pas d'éléments.

    Je détail la fonction

    Car je pense que mon problème viens de là

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    /**
     * class PluginReportsColumn to manage output
     */
    class PluginReportsColumn {
     
       // name of the column in the SQL result set
       public    $name;
       // Fields for ORDER BY when this column is selected
       public $sorton;
       // Label of the column in the report
       private   $title;
       // Extras class for rendering in HTML
       private   $extrafine;
       // Extras class for rendering in HTML in Bold
       private   $extrabold;
       // Manage total for this colum (if handled by sub-type)
       protected $withtotal;
     
     
       function __construct($name, $title, $options=array()) {
     
          $this->name      = $name;
          $this->title     = $title;
     
          // Extras class for each cell
          $this->extrafine = (isset($options['extrafine']) ? $options['extrafine'] : '');
     
          // Extras class for each total cell
          $this->extrabold = (isset($options['extrabold']) ? $options['extrabold'] : "class='b'");
     
          // Enable total for this column (if handle bu subtype)
          $this->withtotal = (isset($options['withtotal']) ? $options['withtotal'] : false);
     
          // Enable sort for this column
          $this->sorton = (isset($options['sorton']) ? $options['sorton'] : false);
       }
     
     
       function showTitle($output_type, &$num) {
     
          if ($output_type != HTML_OUTPUT || !$this->sorton) {
              echo Search::showHeaderItem($output_type, $this->title, $num);
              return;
          }
          $order = 'ASC';
          $issort = false;
          if (isset($_REQUEST['sort']) && $_REQUEST['sort']==$this->name) {
             $issort = true;
             if (isset($_REQUEST['order']) && $_REQUEST['order']=='ASC') {
                $order = 'DESC';
             }
          }
          $link  = $_SERVER['PHP_SELF'];
          $first = true;
          foreach ($_REQUEST as $name => $value) {
             if (!in_array($name,array('sort','order','PHPSESSID'))) {
                $link .= ($first ? '?' : '&amp;');
                $link .= $name .'='.urlencode($value);
                $first = false;
             }
          }
          $link .= ($first ? '?' : '&amp;').'sort='.urlencode($this->name);
          $link .= '&amp;order='.$order;
          echo Search::showHeaderItem($output_type, $this->title, $num,
                                      $link, $issort, ($order=='ASC'?'DESC':'ASC'));
       }
     
     
       function showValue($output_type, $row, &$num, $row_num, $bold=false) {
     
          echo Search::showItem($output_type, $this->displayValue($output_type, $row), $num, $row_num,
                                ($bold ? $this->extrabold : $this->extrafine));
       }
     
     
       function showTotal($output_type, &$num, $row_num) {
     
          echo Search::showItem($output_type,
                                ($this->withtotal ? $this->displayTotal($output_type) : ''),
                                $num, $row_num, $this->extrabold);
       }
     
     
       function displayValue($output_type, $row) {
     
          if (isset($row[$this->name])) {
             return $row[$this->name];
          }
          return '';
       }
     
     
       function displayTotal($output_type) {
          return '';
       }
    }

  12. #12
    Membre expérimenté
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2004
    Messages
    144
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : Vatican

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Mai 2004
    Messages : 144
    Par défaut
    bonjour,

    je pense que le problème viendrai de ta déclaration :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    $report->setColumns(array(new PluginReportsColumn('groupe', 'groupe'),
                              new PluginReportsColumn('lieu', 'lieu'),
    			  new PluginReportsColumn('desktop', 'desktop'),
    			  new PluginReportsColumn('laptop', 'laptop'),
    			  new PluginReportsColumn('portable', 'portable')));
    La fonction SetColums à la quelle tu fais appelle fais partie de la classe PluginReportsAutoReport

    il faudrait voir ce que cette fonction demande comme paramètres. pour ce peux tu mettre le code de la classe PluginReportsAutoReport ou sinon juste la fonction setColumns de cette classe.

  13. #13
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Voici la fonction setColumns de ma classe PluginReportsAutoReport :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
     /**
       * Set columns names (label to be displayed)
       *
       * @param $columns array which contains
       *        sql column name => PluginReportsColumn object
       **/
       function setColumns($columns) {
     
          $this->columns = array();
          foreach ($columns as $name => $column) {
             if ($column instanceof PluginReportsColumn) {
                $this->columns[$column->name] = $column;
             } else {
                // For compat with setColumnsNames - default text mode
                $this->columns[$name] = new PluginReportsColumn($name, $column);
             }
          }
       }

  14. #14
    Membre expérimenté
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2004
    Messages
    144
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : Vatican

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Mai 2004
    Messages : 144
    Par défaut
    tu peux essayer ce code?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
     
    $USEDBREPLICATE= 1;
    $DBCONNECION_REQUIRED= 0;
     
    define('GLPI_ROOT', '../../../..');
    include(GLPI_ROOT."/inc/includes.php");
     
    $report= new PluginReportsAutoReport();
     
     
    $report->setColumns(array(new PluginReportsColumn('groupe', 'groupe'),
                              new PluginReportsColumn('lieu', 'lieu'),
    			  new PluginReportsColumn('desktop', 'desktop'),
    			  new PluginReportsColumn('laptop', 'laptop'),
    			  new PluginReportsColumn('portable', 'portable')));
     
    $query = "SELECT `glpi_groups`.`name` AS groupe, `glpi_locations`.`completename` AS lieu, 
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`='1' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'desktop',
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`='14' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'laptop',
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`='2' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'portable'
     
    FROM `glpi_computers` 
    LEFT JOIN `glpi_groups` ON (`glpi_computers`.`groups_id` = `glpi_groups`.`id`) 
    LEFT JOIN `glpi_locations` ON (`glpi_computers`.`locations_id` = `glpi_locations`.`id`) 
    LEFT JOIN `glpi_computertypes` ON (`glpi_computers`.`computertypes_id` = `glpi_computertypes`.`id`) 
     
    WHERE `glpi_groups`.`name` != 'Informatique' AND `glpi_groups`.`name` != 'Infrastructure' 
    AND `glpi_groups`.`name` != 'Logiciel'
    AND `glpi_computertypes`.`name` != 'Serveur' AND `glpi_computertypes`.`name` != 'Virtual machine'
    AND `glpi_computertypes`.`name` != 'Other' AND `glpi_computertypes`.`name` != 'Unknown'
     
    AND `glpi_computers`.`states_id` = '1' 
     
     
     
    ORDER BY `glpi_groups`.`name`, `glpi_locations.completename`";
     
    $report->setSqlRequest($query);	
    $report->setGroupBy(array('glpi_computers.groups_id','glpi_computers.locations_id'));		  
    $report->execute();

  15. #15
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Merci, Dsl du temp de réponse mais j'ai eu une bonne angine qui à encore quelque trace. J ai essayer ton code et cela me marque toujours :

    Pas d'élément trouvé

    alors que lorsque je passe la requête SQL dans MySQL Wokbench cela me donne un résultat.

    Il doit donc y avoir un problème avec le code en PHP...

    Si je prend un exemple de code pour les colonnes, j'ai :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    $report->setColumns(array(new PluginReportsColumn('entity', $LANG['entity'][0]),
                              new PluginReportsColumn('location', $LANG['common'][15]),
                              new PluginReportsColumnInteger('computernumber',$LANG['Menu'][0]),
                              new PluginReportsColumnInteger('networknumber', $LANG['Menu'][1]),
                              new PluginReportsColumnInteger('monitornumber', $LANG['Menu'][3]),
                              new PluginReportsColumnInteger('printernumber', $LANG['Menu'][2]),
                              new PluginReportsColumnInteger('peripheralnumber', $LANG['Menu'][16]),
                              new PluginReportsColumnInteger('phonenumber', $LANG['Menu'][34])));
    Ou bien un problème de syntaxe de ma requête en PHP :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    $query = "SELECT `glpi_groups`.`name` AS groupe, `glpi_locations`.`completename` AS lieu, 
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`= '1' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'desktop',
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`= '14' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'laptop',
    COUNT((CASE WHEN `glpi_computers`.`computertypes_id`= '2' THEN `glpi_computers`.`id` ELSE NULL END)) AS 'portable'
     
    FROM `glpi_computers` 
    LEFT JOIN `glpi_groups` ON (`glpi_computers`.`groups_id` = `glpi_groups`.`id`) 
    LEFT JOIN `glpi_locations` ON (`glpi_computers`.`locations_id` = `glpi_locations`.`id`) 
    LEFT JOIN `glpi_computertypes` ON (`glpi_computers`.`computertypes_id` = `glpi_computertypes`.`id`) 
     
    WHERE `glpi_groups`.`name` != 'Informatique' AND `glpi_groups`.`name` != 'Infrastructure' 
    AND `glpi_groups`.`name` != 'Logiciel'
    AND `glpi_computertypes`.`name` != 'Serveur' AND `glpi_computertypes`.`name` != 'Virtual machine'
    AND `glpi_computertypes`.`name` != 'Other' AND `glpi_computertypes`.`name` != 'Unknown'
     
    AND `glpi_computers`.`states_id` = '1'
     
    ORDER BY `glpi_groups`.`name`, `glpi_locations.completename`";
    Je vous donnes un code qui fonctionne, celui sur lequel je me suis basé :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    $USEDBREPLICATE         = 1;
    $DBCONNECTION_REQUIRED  = 0;
     
    define('GLPI_ROOT', '../../../..');
    include (GLPI_ROOT . "/inc/includes.php");
     
    $report = new PluginReportsAutoReport();
     
    $report->setColumns(array(new PluginReportsColumn('entity', $LANG['entity'][0]),
                              new PluginReportsColumn('location', $LANG['common'][15]),
                              new PluginReportsColumnInteger('computernumber',$LANG['Menu'][0]),
                              new PluginReportsColumnInteger('networknumber', $LANG['Menu'][1]),
                              new PluginReportsColumnInteger('monitornumber', $LANG['Menu'][3]),
                              new PluginReportsColumnInteger('printernumber', $LANG['Menu'][2]),
                              new PluginReportsColumnInteger('peripheralnumber', $LANG['Menu'][16]),
                              new PluginReportsColumnInteger('phonenumber', $LANG['Menu'][34])));
     
    $query = "SELECT i.`entity`, i.`location`, i.`computernumber`, i.`networknumber`,
                     i.`monitornumber`, i.`printernumber`, j.`peripheralnumber`, l.`phonenumber`
              FROM (SELECT g.`entity`, g.`location`, g.`computernumber`, g.`networknumber`,
                           g.`monitornumber`, h.`printernumber`, g.`id`
                    FROM (SELECT e.`entity`, e.`location`, e.`computernumber`, e.`networknumber`,
                                 f.`monitornumber`, e.`id`
                          FROM (SELECT c.`entity`, c.`location`, c.`computernumber`, d.`networknumber`,
                                       c.`id`
                                FROM (SELECT a.`entity`, a.`location`, b.`computernumber`, a.`id`
                                      FROM (SELECT `glpi_entities`.`completename` AS entity,
                                                   `glpi_locations`.`completename` AS location,
                                                   `glpi_locations`.`id` AS id
                                            FROM `glpi_locations`
                                            LEFT JOIN `glpi_entities`
                                              ON (`glpi_locations`.`entities_id`=`glpi_entities`.`id`) ".
                                            getEntitiesRestrictRequest(" WHERE ", "glpi_locations").") a
                                      LEFT OUTER JOIN (SELECT count(*) AS computernumber,
                                                              `glpi_computers`.`locations_id` AS id
                                                       FROM `glpi_computers`
                                                       WHERE is_deleted=0 AND is_template=0
                                                       ".getEntitiesRestrictRequest(" AND ", "glpi_computers")."
                                                       GROUP BY `glpi_computers`.`locations_id`) b
                                           ON (a.id = b.id)
                                     ) c
                                LEFT OUTER JOIN (SELECT count(*) AS networknumber,
                                                        `glpi_networkequipments`.`locations_id` AS id
                                                 FROM `glpi_networkequipments`
                                                 WHERE is_deleted=0 AND is_template=0
                                                 ".getEntitiesRestrictRequest(" AND ", "glpi_networkequipments")."
                                                 GROUP BY `glpi_networkequipments`.`locations_id`) d
                                     ON (c.id = d.id)
                               ) e
                          LEFT OUTER JOIN (SELECT count(*) AS monitornumber,
                                                  `glpi_monitors`.`locations_id` AS id
                                           FROM `glpi_monitors`
                                           WHERE is_deleted=0 AND is_template=0
                                           ".getEntitiesRestrictRequest(" AND ", "glpi_monitors")."
                                           GROUP BY `glpi_monitors`.`locations_id`) f
                               ON (e.id = f.id)
                         ) g
                    LEFT OUTER JOIN (SELECT count(*) AS printernumber,
                                            `glpi_printers`.`locations_id` AS id
                                     FROM `glpi_printers`
                                     WHERE is_deleted=0 AND is_template=0
                                     ".getEntitiesRestrictRequest(" AND ", "glpi_printers")."
                                     GROUP BY `glpi_printers`.`locations_id`) h
                         ON (g.id = h.id)
                   ) i
              LEFT OUTER JOIN (SELECT count(*) AS peripheralnumber,
                                      `glpi_peripherals`.`locations_id` AS id
                                  FROM `glpi_peripherals`
                                  WHERE is_deleted=0 AND is_template=0
                                  ".getEntitiesRestrictRequest(" AND ", "glpi_peripherals")."
                                  GROUP BY `glpi_peripherals`.`locations_id`) j
                   ON (i.id = j.id)
              LEFT OUTER JOIN (SELECT count(*) AS phonenumber,
                                      `glpi_phones`.`locations_id` AS id
                               FROM `glpi_phones`
                               WHERE is_deleted=0 AND is_template=0
                               ".getEntitiesRestrictRequest(" AND ", "glpi_phones")."
                               GROUP BY `glpi_phones`.`locations_id`) l
                   ON (i.id = l.id)
              ORDER BY i.entity, i.location";
     
    $report->setGroupBy("entity");
    $report->setSqlRequest($query);
    $report->execute();
    je me demande si le problème ne pourrais pas venir de :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    .getEntitiesRestrictRequest()
    Je suis actuellement un peu perdu dans tout ça ...

  16. #16
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    Je remet mon code SQL si besoin :
    Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    SELECT glpi_groups.name AS groupe, glpi_locations.completename AS lieu, 
    COUNT((CASE WHEN glpi_computers.computertypes_id='1' THEN glpi_computers.id ELSE NULL END)) AS 'desktop',
    COUNT((CASE WHEN glpi_computers.computertypes_id='14' THEN glpi_computers.id ELSE NULL END)) AS 'laptop',
    COUNT((CASE WHEN glpi_computers.computertypes_id='2' THEN glpi_computers.id ELSE NULL END)) AS 'portable'
     
    FROM glpi_computers 
     
    LEFT JOIN glpi_groups ON (glpi_computers.groups_id = glpi_groups.id) 
    LEFT JOIN glpi_locations ON (glpi_computers.locations_id = glpi_locations.id) 
    LEFT JOIN  glpi_computertypes ON (glpi_computers.computertypes_id = glpi_computertypes.id) 
     
    WHERE glpi_groups.name != "Informatique" AND glpi_groups.name != "Infrastructure" AND glpi_groups.name != "Logiciel"
    AND glpi_computertypes.name != "Serveur" AND glpi_computertypes.name != "Virtual machine"
    AND glpi_computertypes.name != "Other" AND glpi_computertypes.name != "Unknown"
     
    AND glpi_computers.states_id = '1' 
     
    GROUP BY glpi_computers.groups_id,glpi_computers.locations_id
     
    ORDER BY glpi_groups.name, glpi_locations.completename

  17. #17
    Membre habitué
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2013
    Messages : 13
    Par défaut
    J'ai trouvé une érreur de " ` " dans ma requête. Maintenant, lors de l'éxécution de mon fichier PHP il me retourne une seule ligne qui contient des chiffres qui sont faux. Pouvez vous m'aider ?

Discussions similaires

  1. requête sql sous access
    Par jadey dans le forum Requêtes et SQL.
    Réponses: 2
    Dernier message: 04/08/2006, 21h20
  2. [SQL] Editeur de requête SQL en PHP
    Par lodan dans le forum PHP & Base de données
    Réponses: 6
    Dernier message: 19/07/2006, 17h55
  3. [SQL] Concaténer des requêtes SQL en PHP
    Par brotelle dans le forum PHP & Base de données
    Réponses: 9
    Dernier message: 18/04/2006, 19h53
  4. affichage requête sql sous phppgadmin
    Par kerzut dans le forum PostgreSQL
    Réponses: 3
    Dernier message: 25/02/2005, 12h39
  5. requête mysql sous php
    Par remi59 dans le forum Débuter
    Réponses: 9
    Dernier message: 03/07/2003, 10h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo