PHP - Creating Json Code With Php For Nvd3 Charts
Hi,
Similar Tutorialsi've to populate google charts with dynamic data. the data looks llike. +----+-------+---------+-------+-----------+---------+------+ | id | name | physics | maths | chemistry | biology | sst | +----+-------+---------+-------+-----------+---------+------+ | 1 | Name1 | 10 | 25 | 35 | 42 | 62 | | 2 | Name2 | 80 | 45 | 45 | 45 | 25 | | 3 | Name3 | 63 | 25 | 63 | 36 | 36 | | 4 | Name4 | 82 | 36 | 75 | 48 | 42 | | 5 | Name5 | 45 | 45 | 78 | 25 | 24 | | 6 | Name6 | 36 | 36 | 15 | 75 | 36 | | 7 | Name7 | 99 | 45 | 24 | 24 | 45 | | 8 | Name8 | 45 | 85 | 85 | 85 | 96 | +----+-------+---------+-------+-----------+---------+------+ i have to create google charts based on this such that # namewise - such that when i select a name it displays all subject marks of that particular name in a column chart #markswise - when i select a subject, it displays all the names with marks in that particular subject. conisdiering that data may be added and i've to accumulate that also, for namewise i did // chart.php <?php include("connection.php"); $query = "SELECT name FROM csv GROUP BY name DESC"; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); ?> <!DOCTYPE html> <html> <head> <title>Google charts</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> </head> <body> <br /><br /> <div class="container"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-9"> <h3 class="panel-title">Student Wise Marks Data</h3> </div> <div class="col-md-3"> <select name="name" class="form-control" id="name"> <option value="">Select Student</option> <?php foreach($result as $row) { echo '<option value="'.$row["name"].'">'.$row["name"].'</option>'; } ?> </select> </div> </div> </div> <div class="panel-body"> <div id="chart_area" style="width: 1000px; height: 620px;"></div> </div> </div> </div> </body> </html> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'bar']}); google.charts.setOnLoadCallback(); function load_student_data(name, title) { var temp_title = title + ' '+name+''; $.ajax({ url:"fetch.php", method:"POST", data:{name:name}, dataType:"JSON", success:function(data) { drawStudentwiseChart(data, temp_title); } }); } function drawStudentwiseChart(chart_data, chart_main_title) { var jsonData = chart_data; var data = new google.visualization.DataTable(); data.addColumn('number', 'Physics'); data.addColumn('number', 'Maths'); data.addColumn('number', 'Chemistry'); data.addColumn('number', 'Biology'); data.addColumn('number', 'SST'); $.each(jsonData, function(i, jsonData){ var Physics = jsonData.Physics; var Maths = jsonData.Maths; var Chemistry = jsonData.Chemistry; var Biology = jsonData.Biology; var SST = jsonData.SST; data.addRows([[Physics,Maths,Chemistry,Biology,SST]]); }); var options = { title:chart_main_title, hAxis: { title: "Subjects" }, vAxis: { title: 'Percentage' } }; var chart = new google.visualization.ColumnChart(document.getElementById('chart_area')); chart.draw(data, options); } </script> <script> $(document).ready(function(){ $('#name').change(function(){ var name = $(this).val(); if(name != '') { load_student_data(name, 'Student wise marks data'); } }); }); </script> and in order to fetch data // fetch.php <?php //fetch.php include('connection.php'); if(isset($_POST["name"])) { $query = " SELECT * FROM csv WHERE name = '".$_POST["name"]."' ORDER BY id ASC "; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); foreach($result as $row) { $output[] = array( 'Physics' => $row["Physics"], 'Maths' => $row["Maths"], 'Chemistry' => $row["Chemistry"], 'Biology' => $row["Biology"], 'SST' => $row["SST"], ); } echo json_encode($output); } ?> it diplays a blank page. however when i play with singular values i.e one subject at a time it displays fine Edited March 19, 2019 by zetastreakcan any body tell me why im not getting the value of the profile id $json = '{\"profile_id\":100000503667042,\"sk\":\"info\"}'; $obj = (json_decode($json)); print $obj->{'profile_id'}; Ok I have a unique issue I have a decent sized database for a fix up and modify project I just landed. My problem is my client has a table with plain html, flash, javascript it in. Which generally speaking isn't to much a problem if I we're going the straight php route to get the data from the database. However I'm not so lucky. These people wish to have the element being built by me to use AJAX to give the site a "2.0" feel, which again to a point fine. So all this said and done, I am going using jQuery as my frame for the javascript. The landing page for the script is PHP it handles any potential user input checks before it works its way into the javascript variables to then use JSON through the javascript to another php file which in turn double checks the inputs just incase someone wants to go in to the source find the way to the file its gathering the data from an all else. Then based on the data forms its output. Which I don't know why Ive wasted my time explaining that, we all know how JSON works in concept at least. My issue with this all is, a single column or 2 but ill stick with just the one for now... with these people having stored plain html, javascript, and object tags for flash in the column without any htmlspecialchars or stripslash's or really any security per say in mind. In other words I can go into any column and just copy and paste the code and have it work in an HTML file as if it were typed out for use in HTML alone. So with that, my JSON requests are failing due to the extra quotes, double quotes, slashes, and all else. What I am trying to figure out is, what is my best method to phrase the output of the DB so its friendly for for the JSON request yet can be repieced back together via javascript/jquery. Any takers on that idea? This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=355144.0 I have a submit.php file that includes the following jQuery code: <script> [...] request.done(function( json ) { jQuery('input[name=thumbnail-url]').val(json.thumbnail_url); jQuery('input[name=job_title]').val(json.title); jQuery('textarea[name=htmlcode]').val(json.html); [...] </script> I need to remove jQuery('textarea[name=htmlcode]').val(json.html); and pass the "json.html" value into a PHP variable in another php file (functions.php). The code in the functions.php file is already there. The thing i need to do (and i am seriously struggling with it) is placing the value of json.html into a $phpvariable that i can then call from the function.php file. Do you need any more info for this issue? Thanks. Hello, I'm working on a project that takes a CSV (poorly formated unfortunately) and turns it in charts. What should I use? Maani XML/PHP, Pcharts, ...? There are so many possibilities, I'm lost. What do you guys recommend? thanks (if maani is any good, how do I convert something like Array ( => Array ( => Array ( => FORMULE ENTREE+PLAT [1] => 24 ) [1] => Array ( => FORMULE PLAT+DESSERT [1] => 34 ) ) [1] => Array ( => Array ( => ASSIETTE DE FRITES [1] => 2 ) [1] => Array ( => ASSIETTE MIXTE [1] => 1 ) [2] => Array ( => SALADE AUVERGNATE [1] => 8 ) [3] => Array ( => SALADE CHARENTAISE [1] => 17 ) [4] => Array ( => SALADE DU BURON [1] => 10 ) [5] => Array ( => SALADE FERMIERE [1] => 3 ) ) into a XML file? This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=352327.0 My wife is a Type 1 diabetic and I am trying to put a site together where she can record her blood/glucose readings and analyse the readings.
I am trying to use Google Charts to create a line graph so that she can see if their is a trend during the day when her blood sugar levels peak and trough. But my coding isn't providing any results.
Can anyone see what I am doing wrong?
<?php $level=DB::getInstance()->query("SELECT * FROM tabbyhealth WHERE reading!=0"); foreach ($level->results() as $levelresults) $glucose = $levelresults->reading; $timestamp = date('d M Y h.i A',strtotime($levelresults->timestamp) +18000); ?> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Time of Reading'); data.addColumn('number', 'Blood Glucose Reading'); data.addRows([ ['<?php echo $timestamp; ?>', '<?php echo $glucose; ?>'] ]); var options = { title:'Blood Glucose Monitoring', curveType: 'function', legend: { position: 'bottom' } width:600, height:300 hAxis: { title: 'Date/Time' }, vAxis: { title: 'Reading' } }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <div id="chart_div"></div> </body>I have even tried replacing data.addRows([ ['<?php echo $timestamp; ?>', '<?php echo $glucose; ?>'] ]);with data.addRows([ [0, 0, 0], [1, 10, 5], [2, 23, 15], [3, 17, 9], [4, 18, 10], [5, 9, 5], [6, 11, 3], [7, 27, 19], [8, 33, 25] ]);to see if it is just a problem with reading from my database, but I am still getting nothing - by nothing I mean that no chart is appearing. HI guys Im developing Health site using PHP and mysql. I want to create graphs from using data in the database on weekly basis. so please tell me what is the best method of creating graphs and charts in php thank in advance This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=322864.0 Hello, I am new to pHp and javascript languages and I am trying to do some math calculations in pHp, then display the results with google charts. However, I got stuck with inserting data from pHp using json_encode. It works for the most simple array, with using 2 values. When using array of arrays, it does not work. I believe it could be a syntax errors with all those brackets but I could not figure it out. Thanks for any ideas! <?php // some arrays with dim 2x2 $testarr0 = array( 0.1, 2.5); $testarr = array( 1.0, 3.5); $testarr = array( $testarr0, $testarr ) ; // this is how it looks in pHp $json = json_encode($testarr); echo($json); echo '<br/>'; echo json_encode($json); ?> <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"> </script> <script type="text/javascript"> google.charts.load('current', {'packages':['line']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'x values'); data.addColumn('number', 'y1 '); //var dataArray = <?php echo json_encode($testarr);?>; //document.body.innerHTML = " Data Array with json: " + dataArray ; // defining array here works well /* data.addRows( [ [0.1 ,2.5], [1.0 ,3.5] ] ); */ // this here does not work: data.addRow( <?php echo json_encode($testarr);?> ); // some options for the chart var options = { chart: { title: 'Points over time', }, width: 600, height: 400, axes: { x: { 0: {side: 'top'} } } }; var chart = new google.charts.Line(document.getElementById('line_top_x')); chart.draw(data, google.charts.Line.convertOptions(options)); } </script> </head> <body> <div id="line_top_x" style="width: 900px; height: 500px"></div> </body> </html>
Good morning,
I am doing a small project including google charts API but I am having trouble getting my results into the json format that is required.
Google's documentation states the json format should be:
{ "cols": [ {"id":"","label":"Topping","pattern":"","type":"string"}, {"id":"","label":"Slices","pattern":"","type":"number"} ], "rows": [ {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]}, {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]} ] }the query works perfectly fine thats not the problem but getting it into the above format is proving hard than I expected. The below is what I am trying to do to populate the json data in the correct format. function graphdata() { $array['cols'][] = array('type' => 'string'); $array['cols'][] = array('type' => 'string'); $array['cols'][] = array('type' => 'string'); $result = sqlsrv_query($conn, $query); while($row = sqlsrv_fetch_object($result)){ $array['rows'][] = array('c' => array( array('v'=>'$row->DateCreated->format('d-m-Y')'), array('v'=>$row->UnitPrice)) ); } return $array; } print json_encode(graphdata());I am using MSSQL and not the normal mysql hence the above code, i am a starter when it comes to php so I may be doing something basic totally wrong but I cannot seem to get it to work. Thanks Hi, Posted here as it is in regards to PHP code making MySQL queries. Let's say i had this code below: <?php # Databse query $query = mysql_query("SELECT id, admin, username, first_name, last_name, email FROM `users` WHERE username = '$username' AND password = '$password' LIMIT 1"); # Check login query if(!$query){ echo 'Oops'; } else { echo 'Login Succesful'; } ?> Now this code with slight difference: <?php # Databse query $query = mysql_query("SELECT id, admin, username, first_name, last_name, email FROM `users` WHERE username = '$username' AND password = '$password' LIMIT 1"); # Check login query if(!$query){ echo 'Oops'; } else { if (mysql_num_rows($query) == 1) { echo 'Login Succesful'; } else { echo 'Login Details Invalid'; } } ?> Now my question is in the second lot of code; i am doing a check to ensure that the query is true in terms of username and password match database login credentials by doing mysql_num_rows as in code . Basically do i need to do that extra check in the second lot of code or is the first lot of code fine in checking username and password match database and if not return oops and return Oops if query fails for any other reason ? not sure if i am creating more code that is needed. I am slightly confused see in whether the extra check in second lot of code is needed or not. Could someone please explain in simple terms to me if it is or not and why? Thanks Hello,
I have a website called http://flappycreator.com/ where users can upload multiple images to create their own version of Flappy Bird. As a result of this I created a PHP page that takes a GET param to create a preview image of their game to display in various locations on the website.
Here is an example:
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
My issue is, I have given my users the ability to upload PNGs or JPGs and trying to figure out reliable code to display the preview has become a huge hassle. In the example above the Pac-Man character shows a white background but when you play the game, it is actually transparent. In other situations I am getting extremely bad color distortion. The code I have provided is my final attempt after a ton of trial-and-error and the PNG imagealphablending() and imagesavealpha() commands have shown me the best results, however I don't know what they do.
Please help! Thanks.
<?php $bird_picture = "default/bird.png"; $tube1_picture = "default/tube1.png"; $tube2_picture = "default/tube2.png"; $ground_picture = "default/ground.png"; $bg_picture = "default/bg.png"; // If an id is set, then reset values if (isset ( $_GET ['id'] )) { require ('XXX.php'); $db = new DBAccess (); $query = "SELECT * FROM XXX WHERE XXX = '{$_GET['id']}'"; $result = $db->query ( $query ); $num_results = $result->num_rows; $row = mysqli_fetch_array ( $result ); if ($num_results != 0) { if ($row ['bird_picture'] != "") { $bird_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bird_picture']; } if ($row ['tube1_picture'] != "") { $tube1_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube1_picture']; } if ($row ['tube2_picture'] != "") { $tube2_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube2_picture']; } if ($row ['ground_picture'] != "") { $ground_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['ground_picture']; } if ($row ['bg_picture'] != "") { $bg_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bg_picture']; } } } $temp = explode(".", $bg_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $background = imagecreatefromjpeg($bg_picture); } else { $background = imagecreatefrompng($bg_picture); // Turn off alpha blending and set alpha flag imagealphablending($background, true); imagesavealpha($background, true); } $temp = explode(".", $ground_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $ground = imagecreatefromjpeg($ground_picture); } else { $ground = imagecreatefrompng($ground_picture); // Turn off alpha blending and set alpha flag imagealphablending($ground, false); imagesavealpha($ground, true); } $temp = explode(".", $bird_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $bird = imagecreatefromjpeg($bird_picture); } else { $bird = imagecreatefrompng($bird_picture); // Turn off alpha blending and set alpha flag imagealphablending($bird, false); imagesavealpha($bird, true); } $temp = explode(".", $tube1_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube1 = imagecreatefromjpeg($tube1_picture); } else { $tube1 = imagecreatefrompng($tube1_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube1, false); imagesavealpha($tube1, true); } $temp = explode(".", $tube2_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube2 = imagecreatefromjpeg($tube2_picture); } else { $tube2 = imagecreatefrompng($tube2_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube2, false); imagesavealpha($tube2, true); } imagecopymerge($background, $tube1, 200, -200, 0, 0, 52, 320, 100); imagecopymerge($background, $tube2, 200, 200, 0, 0, 52, 320, 100); imagecopymerge($background, $ground, 0, 320, 0, 0, 336, 112, 100); imagecopymerge($background, $bird, 70, 190, 0, 0, 36, 26, 100); header('Content-Type: image/png'); imagepng($background); # Destroy imagedestroy($background); imagedestroy($ground); imagedestroy($bird); imagedestroy($tube1); imagedestroy($tube2); ?>Attached Files preview.php 3.31KB 1 downloads http://paste.ee/p/OhiWv
The above is a link to a readable version of my code. The XMLHTTPREQUEST worked, and the array was pulled down. Was able to print out the undecoded/unparsed array. However, immediately afterwards, all code stops working.
<script> var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 8 and older xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("POST", "PHPLibrary/selectMemberResults.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(); xhr.onreadystatechange = display_data; var $phparray function display_data() { if (xhr.readyState == 4) { if (xhr.status == 200) { //alert(xhr.responseText); $phparray = xhr.responseText; document.getElementById("suggestion").innerHTML = $phparray; // // //......................................................? // The above line of code is the last thing to print or // to do anything that returns to the browser.... //.......................................................? // All lines below do nothing............................? // } else { //alert('There was a problem with the request.'); } } } document.write("Length of phparray Array :" + $phparray.length + "<"); var output = JSON.parse($phparray, function (key,val) { if ( typeof val === 'string' ) { // regular expression to remove extra white space if ( val.indexOf('\n') !== -1 ) { var re = /\s\s+/g; return val.replace(re, ' '); } else { return val; } } return val; } ); document.write("Length of Array :" + $output.length + "<"); for (var i=0; i < $output.length; i++) { document.getElementById("suggestion").innerHTML = $output[i].MEMBER_NAME; } </script> Hi, Ihave the below array output from a DB query. I need to convert into the bottom array for Google CHarts. Any ideas? $myarray = array( 0 => array( 'year' => 2009, 'month' => "January", 'month_sales' => 524, 'year_totalsales' => 3610 ), 1 => array ( 'year' => 2009, 'month' => 'February', 'month_sales' => 521, 'year_totalsales' => 3610 ), 2 => array ( 'year' => 2009, 'month' => 'March', 'month_sales' => 501, 'year_totalsales' => 3610 ), 3 => array ( 'year' => 2009, 'month' => 'April', 'month_sales' => 601, 'year_totalsales' => 3610 ), 4 => array ( 'year' => 2009, 'month' => 'May', 'month_sales' => 710, 'year_totalsales' => 3610 ), 5 => array ( 'year' => 2009, 'month' => 'June', 'month_sales' => 801, 'year_totalsales' => 3610 ), 6 => array ( 'year' => 2009, 'month' => 'July', 'month_sales' => 991, 'year_totalsales' => 3610 ), 7 => array ( 'year' => 2009, 'month' => 'August', 'month_sales' => 301, 'year_totalsales' => 3610 ), 8 => array ( 'year' => 2009, 'month' => 'September', 'month_sales' => 250, 'year_totalsales' => 3610 ), 9 => array ( 'year' => 2009, 'month' => 'October', 'month_sales' => 322, 'year_totalsales' => 3610 ), 10 => array ( 'year' => 2009, 'month' => 'November', 'month_sales' => 621, 'year_totalsales' => 3610 ), 11 => array ( 'year' => 2009, 'month' => 'December', 'month_sales' => 691, 'year_totalsales' => 3610 ), 12 => array ( 'year' => 2010, 'month' => "January", 'month_sales' => 789, 'year_totalsales' => 1610 ), 13 => array ( 'year' => 2010, 'month' => "February", 'month_sales' => 1409, 'year_totalsales' => 1610 ), 14 => array ( 'year' => 2010, 'month' => "March", 'month_sales' => 550, 'year_totalsales' => 1610 ) ); raw_data=[['January',524,0],['February',521,0],['March',501,0],['April',601,0],['May',710,0],['June',801,0], ['July',991,0],['August',301,0],['September',250,0],['October',322,0],['November',621,0],['December',691,0],['January',789,0],['February',1409,0],['March',550,0],]; raw_data= [ [ month1 , year1 sales figure(zero if no figure), year2 sales figure(zero if no figure).....], [ month1 , year1 sales figure(zero if no figure), year2 sales figure(zero if no figure).....]......]; Thanks all my value, selectname.push(element.name); selectqty.push(element.qty); How to pass Google charts function,
$.each(data, function(index, element) { selectname.push(element.name); selectqty.push(element.qty); google.charts.load('current', { 'packages': ['corechart'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data1 = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); // var data1 = google.visualization.arrayToDataTable([ // [element.name, element.qty], // // // ]); var options = { title: 'Top 5 Best Selling Products' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data1, options); }
hey guys, what i have done so far is got the link to a bbc video feed so when you go to my site the php code will retrive the latest video from bbc and get the link. so i now have $url as having the value of the video but i now need to insert it into the html embed video code. so how can i make this. Code: [Select] <object width="416" height="374" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ep"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="wmode" value="transparent" /><param name="movie" value="http://i.cdn.turner.com/cnn/.element/apps/cvp/3.0/swf/cnn_416x234_embed.swf?context=embed_edition&videoId=world/2009/06/28/penhaul.lok.honduras.cnn" /><param name="bgcolor" value="#000000" /><embed src="http://i.cdn.turner.com/cnn/.element/apps/cvp/3.0/swf/cnn_416x234_embed.swf?context=embed_edition&videoId=world/2009/06/28/penhaul.lok.honduras.cnn" type="application/x-shockwave-flash" bgcolor="#000000" allowfullscreen="true" allowscriptaccess="always" width="416" wmode="transparent" height="374"></embed></object> Hi
I am trying to create a google chart from data in query.php and using the google api to load it. Everything works until I want to change the MetalSourceID from a drop select box.
PHP CODE FOR DROP DOWN BOX:
<form> <select name="users" onchange="showUser(this.value);drawChart();"> <option value=""> Select a Metal: </option> <?php $query = "SELECT TOP(31) tblMetalPrice.MetalSourceID, tblMetalSource.MetalSourceName from tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID=tblMetalSource.MetalSourceID ORDER BY tblMetalPrice.DateCreated DESC "; $result = sqlsrv_query( $conn, $query); while( $row = sqlsrv_fetch_object ($result)) { echo "<option value='".$row->MetalSourceID ."'>". $row->MetalSourceName ."</option>"; } sqlsrv_close( $conn); ?> </select> </form>This works fine and generates all the correct values. One part of this changes contents of a table which works fine. But I also echo the MetalSourceID into the javascript for the google api, JS script below: <script type="text/javascript"> google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart); function drawChart() { var jsonData = $.ajax({ url: "query.php", dataType:"json", async: false, data: { 'MetalSourceID' : <?php $q = intval($_GET['q']); echo $q; ?> } }).responseText; var data = new google.visualization.DataTable(jsonData); var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data); } </script>This then runs the query.php script and returns the google line chart, a copy of the query.php script is below: Hi, So i have HTML table which i'm attempting to turn into executable SQL code which i can then insert into a SQL database table. I'm wondering if anyone has any good ideas for the best way to get this done? I need to extract the data from each of the <tr bgcolor="#EEEEEE">, scrape the text within each <td></td> and then format it in sql. so far i have removed the html not required and created an array by exploding "<tr bgcolor="#EEEEEE">", however, its creating an empty element in the first array index [0], to fix this i have tried $players = array_shift($players); however it removed everything from the array. next i was thinking i would need to remove all html within each array element and add a comma to the end, then i would need to compress it all back together again? would this be the best way to do this? source html <html> <head> <title><br/></title> <style type ="text/css"> body,td,th { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; } th { padding: 5px; text-align: left; } td { padding: 2px; border-style: solid; border-width: 1px } </style> </head> <body> <center><B><br/> </center></B> <p> <table bordercolor="#000000" width="90%" align="center"> <tr bgcolor="#EEEEEE"> <th>UID</th> <th>Name</th> <th>Nat</th> <th>Position</th> <th>Best Pos</th> <th>Age</th> <th>DoB</th> <th>Height</th> <th>Weight</th> <th>Expires</th> <th>Wage</th> <th>Value</th> <th>Aer</th> <th>Cmd</th> <th>Com</th> <th>Ecc</th> <th>Han</th> <th>Kic</th> <th>1v1</th> <th>Pun</th> <th>Ref</th> <th>TRO</th> <th>Thr</th> <th>Cor</th> <th>Cro</th> <th>Dri</th> <th>Fin</th> <th>Fir</th> <th>Fre</th> <th>Hea</th> <th>Lon</th> <th>L Th</th> <th>Mar</th> <th>Pas</th> <th>Pen</th> <th>Tck</th> <th>Tec</th> <th>Agg</th> <th>Ant</th> <th>Bra</th> <th>Cmp</th> <th>Cnt</th> <th>Dec</th> <th>Det</th> <th>Fla</th> <th>Ldr</th> <th>OtB</th> <th>Pos</th> <th>Tea</th> <th>Vis</th> <th>Wor</th> <th>Acc</th> <th>Agi</th> <th>Bal</th> <th>Jum</th> <th>Nat</th> <th>Pac</th> <th>Sta</th> <th>Str</th> </tr> <tr bgcolor="#EEEEEE"> <td>859596</td> <td>Tim Krul</td> <td>NED</td> <td>GK</td> <td>GK</td> <td>31</td> <td>3/4/1988 (31 years old)</td> <td>194 cm</td> <td>83 kg</td> <td>30/6/2022</td> <td>£25,000 p/w</td> <td>£12.75M</td> <td>15</td> <td>13</td> <td>14</td> <td>8</td> <td>13</td> <td>13</td> <td>15</td> <td>12</td> <td>16</td> <td>15</td> <td>12</td> <td>1</td> <td>2</td> <td>1</td> <td>3</td> <td>8</td> <td>4</td> <td>5</td> <td>3</td> <td>2</td> <td>2</td> <td>9</td> <td>4</td> <td>3</td> <td>8</td> <td>11</td> <td>12</td> <td>14</td> <td>13</td> <td>13</td> <td>12</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>15</td> <td>10</td> <td>5</td> <td>13</td> <td>11</td> <td>13</td> <td>14</td> <td>17</td> <td>13</td> <td>8</td> <td>14</td> <td>10</td> </tr> <tr bgcolor="#EEEEEE"> <td>5204730</td> <td>Michael McGovern</td> <td>NIR</td> <td>GK</td> <td>GK</td> <td>34</td> <td>12/7/1984 (34 years old)</td> <td>188 cm</td> <td>86 kg</td> <td>30/6/2021</td> <td>£8,000 p/w</td> <td>£875K</td> <td>12</td> <td>11</td> <td>10</td> <td>2</td> <td>12</td> <td>12</td> <td>12</td> <td>11</td> <td>13</td> <td>8</td> <td>10</td> <td>5</td> <td>2</td> <td>1</td> <td>3</td> <td>9</td> <td>7</td> <td>6</td> <td>3</td> <td>3</td> <td>2</td> <td>7</td> <td>1</td> <td>2</td> <td>5</td> <td>7</td> <td>12</td> <td>14</td> <td>13</td> <td>13</td> <td>11</td> <td>17</td> <td>1</td> <td>12</td> <td>7</td> <td>12</td> <td>15</td> <td>10</td> <td>15</td> <td>10</td> <td>13</td> <td>12</td> <td>12</td> <td>12</td> <td>8</td> <td>15</td> <td>14</td> </tr> </table> <p> <p align="center"> </body> </html>
code i've created so far: <?php // Defining the basic scraping function function scrape_between($data, $start, $end) { $data = stristr($data, $start); // Stripping all data from before $start $data = substr($data, strlen($start)); // Stripping $start $stop = stripos($data, $end); // Getting the position of the $end of the data to scrape $data = substr($data, 0, $stop); // Stripping all data from after and including the $end of the data to scrape return $data; // Returning the scraped data from the function } $myfile = fopen("source.html", "r") or die("Unable to open file!"); $page = fread($myfile,filesize("source.html")); $page = scrape_between($page, '</tr>', '</table>'); $players = explode('<tr bgcolor="#EEEEEE">', $page); echo '<pre>'; print_r($players); echo '</pre>'; fclose($myfile); ?> Edited December 14, 2019 by seany1234 |