Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

In the code below , i'm only able to get PHP arrays in javascript to work when I hard code the value . Is this the only way to get it to work, or is their a way to copy the entire PHP array into Javacript . Right now I'm tempted to just create a function chart() for each set of PHP array values. As in rather then writing function chart(a) , I might write function chart1() , function chart2(), function chart3()...

<?php
            // Configuration
            $hostname = 'host';
            $username = 'user';
            $password = 'pass';
            $database = 'db';
        $score = 'A' ; 
            $secretKey = "myKey"; // Change this value to match the value stored in the client javascript below 
        //$ValueD = 20 ; // this works 
            //$ValueA  ; 
           try {
                $dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
        echo "Connected to database"; // check for connection
        //$dbh->exec("UPDATE Quiz1 SET $score = 1 WHERE Question = 1");  // THIS DOES NOT  
        //$dbh->exec("UPDATE Quiz1 SET B = 1 WHERE Question = 1"); // THIS WORKS

        /*
        function getFruit($conn) {
        $sql = 'SELECT A, B, C, D FROM Quiz1  WHERE QUESTION = 1';
        foreach ($conn->query($sql) as $row) {
           // print $row['B'] . "\t";
          //  print $row['A'] . "\t";
           // print $row['B] . "\n";
        global $ValueA , $ValueB , $ValueC , $ValueD  ;
         $ValueA = $row['A'];// with this I can see the value , but it wont show up in the chart 
        $ValueB = $row['B'] ; 
        $ValueC = $row['C'] ; 
        $ValueD = $row['D'] ; 
        //echo $ValueA ; 

        }

    }*/

        function getFruit($conn) {
        $sql = 'SELECT A, B, C, D , AnswerA , AnswerB, AnswerC, AnswerD FROM Quiz1  ';
        foreach ($conn->query($sql) as $row) {
           // print $row['B'] . "\t";
          //  print $row['A'] . "\t";
           // print $row['B] . "\n";
        global $ValueA , $ValueB , $ValueC , $ValueD , $AnswerA , $AnswerB, $AnswerC, $AnswerD ;
        $ValueA[] = $row['A'];// with this I can see the value , but it wont show up in the chart 
        $ValueB[] = $row['B'] ; 
        $ValueC[] = $row['C'] ; 
        $ValueD[] = $row['D'] ; 
        $AnswerA[] = $row['AnswerA'];// with this I can see the value , but it wont show up in the chart 
        $AnswerB[] = $row['AnswerB'] ; 
        $AnswerC[] = $row['AnswerC'] ; 
        $AnswerD[] = $row['AnswerD'] ; 

        //echo $ValueA ; 

        }

    }
    //for ( i = 0 , i < $AnswerA.length , i++;){
    //echo ($AnswerA[1])
    //}
        getFruit($dbh); 
        for ( $i = 0; $i <= 10; $i++){
        //$h = ",";
    $temp = (($AnswerA[$i]));
    echo $temp . ",";
    }
    //print (array_values($AnswerA));


    }
    catch(PDOException $e)
        {
        echo $e->getMessage();
        }
    ?>






        <head> 


            <!--Load the AJAX API-->
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
        // load each var 

            function chart0(a){

          //(array_values($array))
         // var VaNum = parseFloat(Va);



        var AnswerA1 = '<?php echo ($AnswerA[0]); ?>';
        //var AnswerA = AnswerAt.split(" ");
        var AnswerB1 = '<?php echo ($AnswerB[0]); ?>';
        //var AnswerB = AnswerBt.split(" ");
        var AnswerC1 = '<?php echo ($AnswerC[0]); ?>';
        //var AnswerC = AnswerCt.split(" ");
        var AnswerD1 = '<?php echo ($AnswerD[0]); ?>';


        var AnswerAt = '<?php echo array_values($AnswerA); ?>';
        var AnswerA = AnswerAt.split(" ");
        var AnswerBt = '<?php echo array_values($AnswerB); ?>';
        var AnswerB = AnswerBt.split(" ");
        var AnswerCt = '<?php echo array_values($AnswerC); ?>';
        var AnswerC = AnswerCt.split(" ");
        var AnswerDt = '<?php echo array_values($AnswerD); ?>';
        var AnswerD = AnswerDt.split(" ");
        var Vat = '<?php echo array_values($ValueA); ?>';

        var Va1 = '<?php echo ($ValueA[0]); ?>';
        var Vb1 = '<?php echo ($ValueB[0]); ?>';
        var Vc1 = '<?php echo ($ValueC[0]); ?>';
        var Vd1 = '<?php echo ($ValueD[0]); ?>';

         var VaNum = parseFloat(Va1);
         var VbNum = parseFloat(Vb1);
         var VcNum = parseFloat(Vc1);
         var VdNum = parseFloat(Vd1);
         /* var VbNum = Vb[a];

          var VcNum = Vc[a];

          var VdNum = Vd[a];*/
    // Load the Visualization API and the piechart package.
          google.load('visualization', '1.0', {'packages':['corechart']});

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

          // Callback that creates and populates a data table,
          // instantiates the pie chart, passes in the data and
          // draws it.
          function drawChart($width,$height) {

            // Create the data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');
            data.addColumn('number', 'Slices');
            data.addRows([
              [AnswerA1, VaNum],
              [AnswerB1, VbNum],
              [AnswerC1, VcNum],
              [AnswerD1, VdNum]
              //crap , where not getting the number data here 
              //['Pepperoni', 2]
            ]);

            // Set chart options
            var options = {'title': 'Quiz Results',
                           'width':400,
                           'height':300};

            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart(document.getElementById('chart_div' + a));
            chart.draw(data, options);
          }

          }

          chart0(0);



        </script>
share|improve this question
    
As you can see I've already tried to combine the array values and run split(), but this hasn't worked ... –  Keithsoulasa Jul 26 '12 at 4:41
7  
My suggestion is still json_encode. Have you read the first section of codereview.stackexchange.com/a/13915/7308 ? You can basically build the data into an array and then dump it into JS with var x = <?php echo json_encode($data); ?>; –  Corbin Jul 26 '12 at 6:08
    
OK, I tired Json before, but I tired ruining a split on it . –  Keithsoulasa Jul 26 '12 at 18:43
    
Connected to database Catchable fatal error: Argument 1 passed to getFruit() must be an instance of PDO, null given, called in path~to~file/index.php on line 57 and defined in path~to~file/index.php on line 48 –  Keithsoulasa Jul 26 '12 at 19:03
    
thats the error i'm getting right now –  Keithsoulasa Jul 26 '12 at 19:03
show 2 more comments

2 Answers

First off, why are you defining your functions in the try block? This makes your try/catch statement harder to read due to length and heavy indentation. Remove the functions from the try block.

And be consistent with your style. I'm seeing many inconsistencies here. For instance, you normally put your opening braces "{" on the same line as the preceding function or keyword, but on your catch block its on a newline. There's nothing wrong with either way, but you should pick one and stick with it. This makes me think you just copy-pasted this from somewhere without understanding it. Never copy-paste a code snippet into your own code, especially if you don't understand it. Take the time to type it out. Even if that means you have to alt-tab to the source repeatedly to get it right. This ensures you at least know the syntax so you can use it again if necessary. The best thing to do is google it, or look it up on PHP documentation to fully understand it before using it.

As Corbin pointed out, the best bet would be to use JSON as it is native to JS. I'm not sure what your comment means, " I tired Json before, but I tired ruining a split on it ". What does this mean? I'm assuming some of the confusion is because of possible typos, but I don't know. The only reason I can think of for this not to work is that your PHP version may not support it, which means it is quite old and you should definitely think about upgrading. Otherwise the example Corbin gave should do the trick.

Also, don't use globals. These are bad. If you need a variable outside the current scope, pass it to the session, or make it a return value in a function.

What's with the parenthesis on `$temp? And why is the variable even necessary? You only use it to echo it out again... Just echo it immediately, like you did above that line. By the way, those parenthesis on echo are also unnecessary, but again this is an inconsistency. Some of your echo statements have them, others do not. Again either way would have been fine, so long as it was consistent.

$temp = (($AnswerA[$i]));//These are unnecessary
echo $temp . ",";

In the future, when posting code, separate the sources. For instance, here it would have been beneficial to separate the "working" code from the commented out "non-working" code. This would have given us an idea of what you had tried without competing with the actual information we needed to see what the program was doing. I gave up about halfway through. Not just because of this, but because of all the things I've mentioned above.

share|improve this answer
    
The JS code is from the Google Charts API , and the other stuff is somewhat from a PDO tutorial , although I wrote everything aside from the basic connection code . I'm not sure why but I tired using JSON and it didn't work , the solution I came up with was to inplode the arrays and then run splits to break them apart back into arrays . This is a temp fix, which i will update in the future once I have a better grasp on this –  Keithsoulasa Aug 3 '12 at 19:16
add comment

This is the solution I came up with

// in Javascript

var ArrayA = '<?php echo implode(",",$AnswerA); ?>';
    var Aname = ArrayA.split(",");

I know this isn't the best way to do it,but it works

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.