I'm trying to create a sample bar chart or pie chart from a MySQL data that I have. I know how to use Google Charts and its basic functionality. The question is..How can I integrate my PHP/MySQL data to create a sample Bar or Pie Chart.
I have the simplest data to display: Count of Apples, Banana and Orange.
I can only display them using the basic coding from Google Charts( putting the values in the Google chart codes),but I need to query them from MySQL. Do I need json for this?
Thanks!
A simple example, get the data from your database and pass it into charts, like:
while($r = mysql_fetch_assoc($query)) {
$google_JSON = "{cols: [";
$column = array_keys($r);
foreach($column as $key=>$value){
$google_JSON_cols[]="{id: '".$key."', label: '".$value."'}";
}
$google_JSON .= implode(",",$google_JSON_cols)."],rows: [";
$google_JSON_rows[] = "{c:[{v: '".$r['id']."'}, {v: ".$r['count']."}]}";
}
// you may need to change the above into a function that loops through rows, with $r['id'] etc, referring to the fields you want to inject..
//pass it into google charts data
echo $google_JSON.implode(",",$google_JSON_rows)."]}";
Related
I am creating a plugin for wordpress and I want to manage the curriculum of an Institute. I use fullcalendar in order to display the records from the database, using json. The problem is that I want to create edit and delete buttons on every event (simple links). I try to send html code with json, but I get the html tags as text in the browser page.
Is there a way to add working html to my json?
<?php
//json response view lessons
add_action('wp_ajax_utt_json_calendar','utt_json_calendar');
function utt_json_calendar(){
global $wpdb;
$viewType = $_POST['viewType'];
$viewFilter = $_POST['viewFilter'];
$lessonsTable = $wpdb->prefix."utt_lessons";
$lessons = $wpdb->get_results("SELECT * FROM $lessonsTable WHERE classroomID=$viewFilter;");
$jsonResponse = array();
foreach($lessons as $lesson){
$result[title] = $lesson->lessonID."<a href='#'>asd</a>";
$result[start] = $lesson->datetime;
array_push($jsonResponse,$result);
}
echo json_encode($jsonResponse);
die();
}
?>
Fullcalendar queries that php script and expects text for event.title.
If you want to add links to your events, you need to do this in your FullCalendar options (Javascript).
The FullCalendar option you are looking for is eventRender. It should look something like:
eventRender: function(event, element) {
element.find('.fc-title').append($("<a href='#'>"+event.editlink+"</a>"));
}
It'll look like this fiddle.
And in your PHP, add the property editLink (or whatever you want to name it) to your returned JSON:
foreach($lessons as $lesson){
$result[title] = $lesson->lessonID;
$result[start] = $lesson->datetime;
$result[editLink] = "asd"; //you could use HTML here but it's better in JS
array_push($jsonResponse,$result);
}
There really isn't any way to do what you want only in PHP since you have to modify the FullCalendar options (which has to be done in JS)
.
Have been looking around for a solution to this and have found some help on stack overflow but in most cases the examples I have found are not using arrays formed from a database query. Here is some code for what I am trying to achieve...
$stores = mysql_query("SELECT * FROM Stores");
$staff = mysql_query("SELECT * FROM Staff");
I would like to create two elements, one for stores and another for staff but I want to filter the staff based on the store client side. So if the user selects "Sydney" from the first dropdown, they are presented with only staff that work at the Sydney store in the second dropdown. Then if the user chooses "London" from the first dropdown, the Sydney staff are replaced by the London staff and so on.
My server side scripting is done with PHP and I am able to create the two dropdowns with PHP. But I am stuck on the jQuery to remove the I don't want from the second dropdown.
I know this is possible, because I see it used all the time. I have seen lots of examples of how to manage this but none of the examples use data from the PHP array to insert the .
You need ajax.
When the user selects something in a dropdown, this fires an event that you can process. Inside of this process you take the value of the selection like jQuery('#id_dropdown').val(), and send this via ajax (I like using POST since you dont run into GET request size limits).
You process this on the server side with php, accessing to the database with the value selected and sent via ajax. When you have the right results for the second dropdown you can output it via echo.
Finally, when the response is returned to jQuery, you can insert all the options in the new dropdown.
JAVASCRIPT PART:
Bind event to the first dropdown
Get value of the option selected in the dropdown
Make ajax request
Here is some example code:
var parameters='value_selected='+value_dropdown;
jQuery.Post({
url: '/destiny_when_I_process',
data: parameters,
success: func_callback
});
//here you can imagine a pause, because PHP is processing the data you send by post
//....
//....
//this part is executed when php send the information
function func_callback(response_from_php){
jQuery('#second_dropdown').html(response_from_php);
}
PHP PART:
get value from POST
access database using this value
echo (send response). You send a chain of text (in HTML), really this is not very professional, but is OK for demonstration purposes. Professionals send JSON, since JSON is lighter-weight.
JAVASCRIPT PART (SECOND PART)
in the callback function, you receive the response data via the first parameter
Insert new data in the second dropdown (since the data is already HTML, you do not need to process it)
for the secondary drop down, yes, you'll need some ajax.
You can create a script that go fetch the result coresponding to the store and send back the option listm witch is inserted in the ooption.
Using jquery and php you'll need a few thing.
A php file to get the result and return the options. (let say getStaff.php)
<?php
//get the store id by post is it is set
if (isset($_POST['store->id']) $store_id = mysqli_real_escape_string($_POST['store_id']);
//get the data !! notice the WHERE caluse
$r = mysql_query("SELECT * FROM Staff" *WHERE store=''$store->is*);
//split the data in the array
$staffs=array();
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$staff->id=$assoc['id'];
$staff->name=$assoc['name'];
//and so on for each colum in your table.
array_push($staffs, $assoc);
}
//echo the result as option
foreach ($staffs as $staff) echo "<option value='$staff->id'>$staff->name</option>";
?>
In you first select, add
onchange="$.post('getStaff.php', {store_id:$(this).val()}, function (data){ $('#staff_select').html(data);});"
and add an id to your second select (staff_select) in this ecample.
As an explanation: When the 1st dropdown change, it send a request to getStaff.php with the store_id as a POST argument. The php sript get the syaff according to the store Id and bring back a list of option tags for your secondary select. Than jquery add the 'data' to your secondary select and VOilĂ !
Hope tih sis clear cause it's a bunch of little thing together that will make it work. Sorry if it's seems sloppy as an answer but it's really simple once you know it.
Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....
Thanks to http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/ for the tutorial.
And thanks to everyone here.
PHP to build for the first :
function agency_select() {
include('../include/dbase.php');
$agencies = $pdo->query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName");
$opt = '';
while ($age_array = $agencies->fetch(PDO::FETCH_ASSOC)) {
$opt .= '<option value="'.$age_array['AgencyId'].'">'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'</option>'."\n\t\t\t\t\t\t\t";
}
return $opt;
}
HTML for the two elements:
<label for="AgencyId">Client/Agency:</label>
<select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden">
<?php echo agency_select(); ?>
</select>
<label for="Contact">Contact: </label>
<select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden">
<option value="">----Select Client/Agency----</option>
</select>
AJAX file:
if(isset($_POST['AgencyId'])) {
include('../include/dbase.php');
$option = '<option value="">----Select Contact----</option>';
$query = $pdo->prepare("SELECT * FROM client WHERE AgencyId= ? AND Status='active' ORDER BY FirstName");
$result = $query->execute(array($_POST['AgencyId'])));
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$option .= '<option value="'.$row['id'].'">'.$row['FirstName'].' '.$row['LastName'].'</option>';
}
echo $option;
}
jQuery:
$(document).ready(function () {
update_contacts();
});
function update_contacts() {
$('#AgencyId').change(function() {
$('#Contact').fadeOut();
$('#loader').show();
$.post('../ajax/ajax_contact_select.php', {
AgencyId: $('#AgencyId').val()
}, function (response) {
setTimeout("finishajax('Contact', '"+escape(response)+"')", 400);
});
return false;
});
}
function finishajax(id,response) {
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
i'll try to help you as much as i can a explain it.
mysql_query, you sould use mysqli btw, mtsql being decrecated, return a result set.
This means you will have all the records from your query. You need to brak down your result into before you can work with it. This is done by using methids like mysql_fetch_assoc, mysql_fetch_row, etc. There something like fetch to array to but i don't master it so i will use fetch assoc, for this reply.
So once you have yoru result set, $stores & $staff in your case, you then call a while loop on your results to get th data as in:
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$stores->id=$assoc['id'];
$stores->name=$assoc['name'];
//and so on for each colum in your table.
array_push($stores, $assoc);
}
Then you can export it as you want.
in you case would be something like
foreach ($stores as $store) echo "<option value='$store->id'>$store->name</option>";
I storngly suggest you take alook at http://php.net/manual/en/function.mysql-fetch-array.php witch will do the same a fetch_assoc bu with an array with the columname as key.
I am trying to create a piechart dynamically by using Google Chart api. i am taking values from the database. I am not getting how exactly this can be done.
$resultViewed = $this->model_report_product->getMostViewed();
$stringResult ="var data= google.visualization.arrayToDataTable([ ['Product', 'Views'],";
foreach($resultViewed as $results)
{
$stringResult = $stringResult . "['".$results['name']."',".$results['quantity']."],";
break;
}
$stringResult .= "]);";
$this->data['Viewed'] = $stringResult;
When i run this, it gives Chart heading but pie chart is not displayed but it says No Data.
You can't pass a variable in memory between php to html. You have to print it out to pass it to html. So where you have:
return $stringResult;
you should print it out like:
print $stringResult;
Im trying to learn php by doing a little project using apache server. I have a php page where I want to display a bar chart with jqplot using data i pull from a MySql query. I already have a query working giving me the data i want. The problem is i dont know how to implement this into a jqplot graph. Im guessing i need to make an ajax call but if i can avoid that i would like to. my php page code so far is here http://snipt.org/oknnl2.
the javascript for the bar chart is here http://snipt.org/oknoi3.
i want the chart to render in div id=chartdiv thats on line 177. I have to visualize like 6 charts. if i can get some help on doing this one, im sure i can use the same process to build the others.
PHP cannot create the javascript plot and send it downstream to the client, but you don't have to make an actual AJAX call after the page is loaded either. Simple javascript once the page loads will suffice. If you retrieve the data you need at the PHP level, you can then make it available to javascript in the HTML received by the client. The steps to make this happen:
First, use PHP to retrieve the data you need from the MySQL database.
Then, output the plot data you retrieved using PHP inside a javascript
code block as part of the HTML that PHP sends to the client.
Execute the javascript with the data seeded by PHP on page load.
So, a simplified example:
<?php
// Retrieve plot data from mysql
$q = '...';
$r = mysql_query($q);
$plot_row1 = array();
$plot_row2 = array();
$plot_row3 = array();
while ($row = mysql_fetch_array($r)) {
// append values to $plot_row1, $plot_row2 and $plot_row3 arrays
}
$my_page_title = 'My first PHP/JS Combo Foray';
?>
<html>
<head>
<script type="text/javascript" src="/scripts/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/scripts/my_plotter.js"></script>
</head>
<body>
<h1><?php echo $my_page_title; ?></h1>
<div id="chartdiv">
Hold on, javascript is loading the plot ...
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
// we're combining the php array elements into a comma separated list
// so that when the code is output javascript thinks it's an array.
// if the $plot_row1 = array(1, 2, 3) then we'd get this:
//
// row1 = [1, 2, 3];
//
// if you needed quotes around the imploded php array values (if they
// are strings where javascript is concerned) you could do this instead:
//
// row1 = ["<?php echo substr(implode('","', $plot_row1), 0, -2); ?>"];
row1 = [ <?php echo rtrim(implode(',', $plot_row1), ','); ?> ];
row2 = [ <?php echo rtrim(implode(',', $plot_row2), ','); ?> ];
row3 = [ <?php echo rtrim(implode(',', $plot_row3), ','); ?> ];
// call your js function that creates the plot
showBrittleness(row1,row2,row3);
// add whatever js code you need to append the plot to $('#chartdiv')
}
</script>
UPDATE
According to a cursory examination of the jqplot docs, if you edit line 12 of the javascript you link from this:
var plot1 = $.jqplot('chart1', [s1, s2], {
To this:
var plot1 = $.jqplot('chartdiv', [s1, s2], {
Your function should render the plot in the 'chartdiv' id element. It seems the first argument to the $.jqplot function is the element in which to create it ...
I have a MySQL database with a table full of geographic points, latitudes and longitudes. I want these coordinates displayed on a Google map as points. Is it possible for JavaScript to directly access the database or would I need to do that first using PHP?
Yes, it's possible and you'd have to use PHP to retrieve your points from the database. For examples of the Google part of your request, have a look at the Google Maps Javascript API V3 reference and update your question when you've put some code together.
You would need some sort of server side language to be involved. Likely ajax/json request or pulling an XML file and looping through the data. If you're more comfortable with PHP you would loop through your results within a script tag:
<script type="text/javascript">
var mapArray = new Array;
<?php
$i = 0;
$result = mysql_query('SELECT * FROM location');
while ($row = mysql_fetch_assoc($result)) {
echo 'mapArray[' .$i++ . '] = new Array(' . $row['lat'] . ',
' . $row['lng'] . '");
';
}
?>
for (var i in mapArray) {
var myLatLng = new GLatLng(mapArray[i][0], mapArray[i][1]);
GMarker(myLatLng);
}
</script>
It is possible to use a PHP script as a link between JavaScript and the SQL database witht he use of the JavaScript XMLHttpRequest object.