Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

in the following code I have 2 javascript vars that I need to pass to a google charts javascript function . Now of these two vars , one $ValueA is set to be data retrieved from a SQL query , the second $ValueD is just a var that is always = to 20 that I put for testing purposes . Now what I need to do is tell the Javacript to yield for how many seconds it takes for the query to complete ( I know the command to do this in unity is yield Wait For Seconds, but it doesn't look like you can do that in normal Javascript . For testing I print out the $ValueA var , and it prints successfully, but wont insert it self in the chart .

    <html>
    <?php
            // Configuration
            $hostname = host;
            $username = 'user';
            $password = 'pass';
            $database = 'dbname';
        $score = 'A' ; 
            $secretKey = "Key"; // Change this value to match the value stored in the client javascript below 
        $ValueD = 20 ; // this works 
            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";
        $ValueA = $row['A'];// with this I can see the value , but it wont show up in the chart 
        echo $ValueA ; 
        }

    }

        getFruit($dbh); 



    }
    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">
/// how do I yield here until we have a value to $ValueA ????       
var stack = '<?php echo $ValueD; ?>';
          var stackn = parseFloat(stack);
        var stacked = '<?php echo $ValueA; ?>';
          var stackedn = parseFloat(stacked);
    // 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() {

            // Create the data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');
            data.addColumn('number', 'Slices');
            data.addRows([
              ['Mushrooms', stackedn],
              ['Onions', stackn],
              ['Olives', 1],
              ['Zucchini', 1],
              ['Pepperoni', 2]
            ]);

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

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

      <body>
        <!--Div that will hold the pie chart-->
        <div id="chart_div"></div>
      </body>
    </html>
share|improve this question

closed as off topic by sepp2k Jul 23 '12 at 16:27

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

Main Answer

I tend to lean on json_encode for this type of thing:

function getFruit(PDO $conn) { //the PDO makes it so that $conn has to be a PDO instance
    $sql = 'SELECT A, B, C, D FROM Quiz1  WHERE QUESTION = 1';
    //Returning data allows you to choose to print it, but you don't have to.
    //If you print inside of the function, you cannot choose to not print it.
    //In other words, for the sake of flexibility, functions very rarely
    //directly print.
    return $conn->query($sql)->fetchAll();
}

echo "var data = " . json_encode(getFruit($conn));

I like to use json_encode for this because it handles the annoyances of proper escaping and formatting automatically, and you can typically just plop it in the middle of existing JS.

If it were an int or a string I wouldn't use json_encode, but for any non-scalar type, json_encode is almost always the way to go for inlining data into JS from PHP.

Example output

The output of the json_encode will look something like:

var data = [{"A": 5, "B": 6, "C": 2, "D": 1}, {"A": 3, "B": 5, "C": 1, "D": 8}];

The important thing to note is that it's essentially an array of objects (it may also be an object of objects if json_encode decides to use the array keys instead of treating it as a plain array.)

To access the first A, you could do: data[0].A or data[0]['A'].

To loop through them all:

var i;
for (i = 0; i < data.length; ++i) {
    console.log("data[" + i + "].A = " + data[i].A);
}

Notes

You cannot have a try block without a catch. That's considered a syntax error.


Also, you have to set PDO to use exceptions as by default it does not. (I strongly believe that exceptions should be the default -- and only -- behavior, but wooo PHP!)

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
share|improve this answer
Much thanks Corbin !, I ended up recoding the query code from yesterday in PDO( since its supposed be a better way of doing PHP SQL access . I will try this in a bit – Keithsoulasa Jul 23 '12 at 0:51
But is their a way to just add a delay to the javascript so it waits until we can get the value of $ValueA before running ? – Keithsoulasa Jul 23 '12 at 0:57
@user1539152 Did you edit your question or did I completely overlook half the code earlier? Super confused now... :). Anyway, PHP runs before JavaScript. The PHP execution will be completely finished before it's even sent to the client. So, you can just output the $valueA in the JavaScript. If you need to grab data on the fly, you can always use AJAX to second an additional request back to the server – Corbin Jul 23 '12 at 1:04
I think you just overlooked the code, right now valueA isn't being read by the javascript at all , I think its because i'm running SQL queries to get data ... Although I'm really not sure since I normally only code in C# Can you send me a link to this AJAX( i'm completely new to web programming . – Keithsoulasa Jul 23 '12 at 1:19
And ValueA is disaplayed by the echo function i'm running , so I think I just need to find a way force the Javascript function to wait until the query is completed – Keithsoulasa Jul 23 '12 at 1:26
show 6 more comments

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