SORU
21 EKİM 2012, Pazar


PHP MySQL Google Chart JSON - Tam Örnek

Bir sürü Google Grafik veri kaynağı olarak MySQL tablo verileri kullanarak oluşturmak için iyi bir örnek bulmak için aradım. Birkaç gün sonra aradım ve birkaç örnek Google Grafik (pasta, çubuk, sütun, tablo) PHP ve MySQL bir arada kullanarak oluşturmak için kullanılabilir olduğunu fark etti. Sonunda bir örnek çalışma başardı.

Daha önce StackOverflow çok yardım aldım, bu sefer bazı döneceğim.

İki örnek var; birisi Ajax kullanır ve diğer değildir. Bugün, sadece non-Ajax örnek göstereceğim.

Kullanımı:

    Requirements: PHP, Apache and MySQL

    Installation:

      --- Create a database by using phpMyAdmin and name it "chart"
      --- Create a table by using phpMyAdmin and name it "googlechart" and make 
          sure table has only two columns as I have used two columns. However, 
          you can use more than 2 columns if you like but you have to change the 
          code a little bit for that
      --- Specify column names as follows: "weekly_task" and "percentage"
      --- Insert some data into the table
      --- For the percentage column only use a number

          ---------------------------------
          example data: Table (googlechart)
          ---------------------------------

          weekly_task     percentage
          -----------     ----------
          Sleep           30
          Watching Movie  10
          job             40
          Exercise        20    

PHP-MySQL-JSON-Google Grafik Örneği:

    <?php
$con=mysql_connect("localhost","Username","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart, you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("SELECT * FROM chart");

/*
---------------------------
example data: Table (Chart)
--------------------------
weekly_task     percentage
Sleep           30
Watching Movie  40
work            44
*/

$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')

);

$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['Weekly_task']); 

    // Values of each slice
    $temp[] = array('v' => (int) $r['percentage']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>

<html>
  <head>
    <!--Load the Ajax API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

PHP-PDO-JSON-MySQL-Google Grafik Örneği:

<?php
    /*
    Script  : PHP-PDO-JSON-mysql-googlechart
    Author  : Enam Hossain
    version : 1.0

    */

    /*
    --------------------------------------------------------------------
    Usage:
    --------------------------------------------------------------------

    Requirements: PHP, Apache and MySQL

    Installation:

      --- Create a database by using phpMyAdmin and name it "chart"
      --- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
      --- Specify column names as follows: "weekly_task" and "percentage"
      --- Insert some data into the table
      --- For the percentage column only use a number

          ---------------------------------
          example data: Table (googlechart)
          ---------------------------------

          weekly_task     percentage
          -----------     ----------

          Sleep           30
          Watching Movie  10
          job             40
          Exercise        20     


    */

    /* Your Database Name */
    $dbname = 'chart';

    /* Your Database User Name and Passowrd */
    $username = 'root';
    $password = '123456';

    try {
      /* Establish the database connection */
      $conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      /* select all the weekly tasks from the table googlechart */
      $result = $conn->query('SELECT * FROM googlechart');

      /*
          ---------------------------
          example data: Table (googlechart)
          --------------------------
          weekly_task     percentage
          Sleep           30
          Watching Movie  10
          job             40
          Exercise        20       
      */



      $rows = array();
      $table = array();
      $table['cols'] = array(

        // Labels for your chart, these represent the column titles.
        /* 
            note that one column is in "string" format and another one is in "number" format 
            as pie chart only required "numbers" for calculating percentage 
            and string will be used for Slice title
        */

        array('label' => 'Weekly Task', 'type' => 'string'),
        array('label' => 'Percentage', 'type' => 'number')

    );
        /* Extract the information from $result */
        foreach($result as $r) {

          $temp = array();

          // the following line will be used to slice the Pie chart

          $temp[] = array('v' => (string) $r['weekly_task']); 

          // Values of each slice

          $temp[] = array('v' => (int) $r['percentage']); 
          $rows[] = array('c' => $temp);
        }

    $table['rows'] = $rows;

    // convert data into JSON format
    $jsonTable = json_encode($table);
    //echo $jsonTable;
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

    ?>


    <html>
      <head>
        <!--Load the Ajax API-->
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">

        // Load the Visualization API and the piechart package.
        google.load('visualization', '1', {'packages':['corechart']});

        // Set a callback to run when the Google Visualization API is loaded.
        google.setOnLoadCallback(drawChart);

        function drawChart() {

          // Create our data table out of JSON data loaded from server.
          var data = new google.visualization.DataTable(<?=$jsonTable?>);
          var options = {
               title: 'My Weekly Plan',
              is3D: 'true',
              width: 800,
              height: 600
            };
          // Instantiate and draw our chart, passing in some options.
          // Do not forget to check your div ID
          var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
          chart.draw(data, options);
        }
        </script>
      </head>

      <body>
        <!--this is the div that will hold the pie chart-->
        <div id="chart_div"></div>
      </body>
    </html>

PHP-MySQLi-JSON-Google Grafik Örneği

<?php
/*
Script  : PHP-JSON-MySQLi-GoogleChart
Author  : Enam Hossain
version : 1.0

*/

/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------

Requirements: PHP, Apache and MySQL

Installation:

  --- Create a database by using phpMyAdmin and name it "chart"
  --- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
  --- Specify column names as follows: "weekly_task" and "percentage"
  --- Insert some data into the table
  --- For the percentage column only use a number

      ---------------------------------
      example data: Table (googlechart)
      ---------------------------------

      weekly_task     percentage
      -----------     ----------

      Sleep           30
      Watching Movie  10
      job             40
      Exercise        20     


*/

/* Your Database Name */

$DB_NAME = 'chart';

/* Database Host */
$DB_HOST = 'localhost';

/* Your Database User Name and Passowrd */
$DB_USER = 'root';
$DB_PASS = '123456';





  /* Establish the database connection */
  $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

   /* select all the weekly tasks from the table googlechart */
  $result = $mysqli->query('SELECT * FROM googlechart');

  /*
      ---------------------------
      example data: Table (googlechart)
      --------------------------
      Weekly_Task     percentage
      Sleep           30
      Watching Movie  10
      job             40
      Exercise        20       
  */



  $rows = array();
  $table = array();
  $table['cols'] = array(

    // Labels for your chart, these represent the column titles.
    /* 
        note that one column is in "string" format and another one is in "number" format 
        as pie chart only required "numbers" for calculating percentage 
        and string will be used for Slice title
    */

    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')

);
    /* Extract the information from $result */
    foreach($result as $r) {

      $temp = array();

      // The following line will be used to slice the Pie chart

      $temp[] = array('v' => (string) $r['weekly_task']); 

      // Values of the each slice

      $temp[] = array('v' => (int) $r['percentage']); 
      $rows[] = array('c' => $temp);
    }

$table['rows'] = $rows;

// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;


?>


<html>
  <head>
    <!--Load the Ajax API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

CEVAP
23 ŞUBAT 2015, PAZARTESİ


Ben şahsen aşağıdaki kodu "hepsi benim komut içinde aramadan paketi." dataManagement kullanın Roxygen dokümantasyon ve örnekler vardır. Aslında sadece Ara ()belge ve doxygen C kodu, koştu src/ . Doktor koymak. enst/doxygen Paketiniz HUYSUZ hazır olması.

R belgelerine R için tasarlanıyorson kullanıcılardeğil bakmak için C kodunu bilmiyordum entegre C kodu belgelerinde klasik R belgelerine ama iyi olur pratik kopyasını elde edilen C belgeleri olarak bir "vignette".

    library("testthat")
    library("devtools")

    #' @title Replace a value for a given tag on file in memory
    #' @description Scan the lines and change the value for the named tag if one line has this tag, 
    #'    add a line at the end if no line has this tag and return a warning if several lines
    #'    matching the tag
    #' @param fileStrings A vector with each string containing a line of the file
    #' @param tag The tag to be searched for 
    #' @param newVal The new value for the tag
    #' @return The vector of strings with the new value
    #' @examples
    #' fakeFileStrings <- c("Hello = world","SURE\t= indeed","Hello = you")
    #' 
    #' expect_warning(ReplaceTag(fakeFileStrings,"Hello","me"))
    #' 
    #' newFake <- ReplaceTag(fakeFileStrings,"SURE","me")
    #' expect_equal(length(newFake), length(fakeFileStrings))
    #' expect_equal(length(grep("SURE",newFake)), 1)
    #' expect_equal(length(grep("me",newFake)), 1)
    #' 
    #' newFake <- ReplaceTag(fakeFileStrings,"Bouh","frightened?")
    #' expect_equal(length(newFake), length(fakeFileStrings) 1)
    #' expect_equal(length(grep("Bouh",newFake)), 1)
    #' expect_equal(length(grep("frightened?",newFake)), 1)
    ReplaceTag <- function(fileStrings,tag,newVal){
        iLine <- grep(paste0("^",tag,"\\>"),fileStrings)
        nLines <- length(iLine)
        if(nLines == 0){
            line <- paste0(tag,"\t= ",newVal)
            iLine <- length(fileStrings) 1
        }else if (nLines > 0){
            line <- gsub("=.*",paste0("= ",newVal),fileStrings[iLine])
            if(nLines >1){
                warning(paste0("File has",nLines,"for key",tag,"check it up manually"))
            }
        }
        fileStrings[iLine] <- line
        return(fileStrings)
    }
    #' Prepares the R package structure for use with doxygen
    #' @description Makes a configuration file in inst/doxygen
    #'     and set a few options: 
    #'     \itemize{
    #'        \item{EXTRACT_ALL = YES}
    #'        \item{INPUT = src/}
    #'        \item{OUTPUT_DIRECTORY = inst/doxygen/}
    #'     }
    #' @param rootFolder The root of the R package
    #' @return NULL
    #' @examples 
    #' \dontrun{
    #' DoxInit()
    #' }
    #' @export
    DoxInit <- function(rootFolder="."){
        doxyFileName <- "Doxyfile"
        initFolder <- getwd()
        if(rootFolder != "."){
            setwd(rootFolder)
        }
        rootFileYes <- length(grep("DESCRIPTION",dir()))>0
        # prepare the doxygen folder
        doxDir <- "inst/doxygen"
        if(!file.exists(doxDir)){
            dir.create(doxDir,recursive=TRUE)
        }
        setwd(doxDir)

        # prepare the doxygen configuration file
        system(paste0("doxygen -g ",doxyFileName))
        doxyfile <- readLines("Doxyfile")
        doxyfile <- ReplaceTag(doxyfile,"EXTRACT_ALL","YES")
        doxyfile <- ReplaceTag(doxyfile,"INPUT","src/")
        doxyfile <- ReplaceTag(doxyfile,"OUTPUT_DIRECTORY","inst/doxygen/")
        cat(doxyfile,file=doxyFileName,sep="\n")
        setwd(initFolder)
        return(NULL)
    }

    #' devtools document function when using doxygen
    #' @description Overwrites devtools::document() to include the treatment of 
    #'    doxygen documentation in src/
    #' @param doxygen A boolean: should doxygen be ran on documents in src?
    #'     the default is TRUE if a src folder exist and FALSE if not
    #' @return The value returned by devtools::document()
    #' @example
    #' \dontrun{
    #' document()
    #' }
    #' @export
    document <- function(doxygen=file.exists("src")){
        if(doxygen){
            doxyFileName<-"inst/doxygen/Doxyfile"
            if(!file.exists(doxyFileName)){
                DoxInit()
            }
            system(paste("doxygen",doxyFileName))
        }
        devtools::document()
    }

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • MC JIN'S OLD YouTube CHANNEL

    MC JIN'S OLD

    2 Kasım 2008
  • calicoJake

    calicoJake

    29 EKİM 2007
  • Emotional Trancer

    Emotional Tr

    4 Mart 2010