help in php file_get_contents - php

i have this file C:\\xampp\htdocs\exact\sample_pie.php that contains a graph. here's the code:
<?php
include("phpgraphlib.php");
include("phpgraphlib_pie.php");
include("connection.php");
$graph=new PHPGraphLibPie(400,200);
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('exact');
$querypa = "SELECT COUNT(nature) FROM approved WHERE nature='Parade'";
$resultpa = mysql_query($querypa);
$printpa = mysql_result($resultpa,0);
$querycs = "SELECT COUNT(nature) FROM approved WHERE nature='Community Service'";
$resultcs = mysql_query($querycs);
$printcs = mysql_result($resultcs,0);
$queryga = "SELECT COUNT(nature) FROM approved WHERE nature='General Assembly'";
$resultga = mysql_query($queryga);
$printga = mysql_result($resultga,0);
$querypl = "SELECT COUNT(nature) FROM approved WHERE nature='Play/Showcase/Socio-Cultural Show/Film Showing'";
$resultpl = mysql_query($querypl);
$printpl = mysql_result($resultpl,0);
$queryco = "SELECT COUNT(nature) FROM approved WHERE nature='Competition/Sportsfest'";
$resultco = mysql_query($queryco);
$printco = mysql_result($resultco,0);
$queryfr = "SELECT COUNT(nature) FROM approved WHERE nature='Fund Raising'";
$resultfr = mysql_query($queryfr);
$printfr = mysql_result($resultfr,0);
$queryse = "SELECT COUNT(nature) FROM approved WHERE nature='Seminar/Convention/Conference/Training'";
$resultse = mysql_query($queryse);
$printse = mysql_result($resultse,0);
$totalAct=$printpa+$printga+$printpl+$printcs+$printco+$printfr+$printse;
$avepa=($printpa/$totalAct)*100;
$avecs=($printcs/$totalAct)*100;
$avega=($printga/$totalAct)*100;
$avepl=($printpl/$totalAct)*100;
$aveco=($printco/$totalAct)*100;
$avefr=($printfr/$totalAct)*100;
$avese=($printse/$totalAct)*100;
$pa=number_format($avepa,2);
$cs=number_format($avecs,2);
$ga=number_format($avega,2);
$pl=number_format($avepl,2);
$co=number_format($aveco,2);
$fr=number_format($avefr,2);
$se=number_format($avese,2);
$data=array("Parade"=>$pa, "General Assembly"=>$ga, "Play/Showcase/Socio-Cultural Show/Film Showing"=>$pl, "Community Service"=>$cs, "Competition/Sportsfest"=>$co, "Fund Raising"=>$fr, "Seminar/Convention/Conference/Training"=>$se);
$graph->addData($data);
$graph->setTitle("Total Activities per Nature of Activity");
$graph->setPrecision(2);
$graph->setLabelTextColor("0,0,0");
$graph->setLegendTextColor("0,0,0");
$graph->setGradient("210,245,255","pastel_purple");
$graph->createGraph();
?>
how can i get the graph as a .jpg through php script? i tried this file_get_contents("C:\\xampp\htdocs\exact\sample_pie.php");
but it only outputs this:
$pa, "General Assembly"=>$ga, "Play/Showcase/Socio-Cultural Show/Film Showing"=>$pl, "Community Service"=>$cs, "Competition/Sportsfest"=>$co, "Fund Raising"=>$fr, "Seminar/Convention/Conference/Training"=>$se); $graph->addData($data); $graph->setTitle("Total Activities per Nature of Activity"); $graph->setPrecision(2); $graph->setLabelTextColor("0,0,0"); $graph->setLegendTextColor("0,0,0"); $graph->setGradient("210,245,255","pastel_purple"); $graph->createGraph(); ?>
please help me. thanks.

Using file_get_contents() like that is only going to retrieve the script itself. That text is what the file contains and that's what file_get_contents() does; exactly what it says on the tin.
Try looking at the documentation for PHPGraphLib or in the source code failing that. There should be some sort of save method you can call instead of createGraph() or maybe you can just pass a filename parameter to createGraph().

On a sidenote, I should mention that your script is a lot more complicated than it should be. Everything between mysql_select_db() and $graph->addData() could be rewritten into something like this:
$data = array(
'Parade' => 0,
'Community Service' => 0,
'General Assembly' => 0,
'Play/Showcase/Socio-Cultural Show/Film Showing' => 0,
'Competition/Sportsfest' => 0,
'Fund Raising' => 0,
'Seminar/Convention/Conference/Training' => 0
);
$sql = "SELECT nature, COUNT(*) AS cnt
FROM approved
WHERE nature IN ('" . implode("','", array_keys($data)) . "')
GROUP BY nature";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$data[$row['nature']] = $row['cnt'];
}
$totalAct = array_sum($data);
foreach ($data as $nature => &$value)
{
$value = number_format(100 * $value / $totalAct, 2);
}
For the rest, consult the documentation of your graph library as Ollie Saunders suggested.

<img src="/exact/sample_pie.php" />
You may want to use header() to set the appropriate Content-type from within sample_pie.php.

Related

User Online List PHP

I'm trying to make a online user list output all my usernames in a row like this (username, username, username)
The code I'm trying:
$result2 = $db->query("SELECT * FROM `online`");
$fetched2 = $result2->fetch_assoc();
$user_id = $fetched2['user_id'];
$result = $db->query("SELECT * FROM `users` WHERE id = $user_id");
while ($fetched = $result->fetch_assoc())
{
$users_arr[] = array("username"=> $fetched['username']);
}
But it's only returning 1 username from online table and not all in a row, how can i do this?
return json_encode(array("status" => 200, "message" => $users_arr)));
This only outputted 1 username, and also it's outputted in json format which i do not want, i want it outputted like so: User, User, User and not like [{'username': 'vanilla'}]"
Can someone please show me the correct way of using an array or a solution to my problem, thanks!
UPDATE:
Tried this and it worked, but now the dilemma is how do i make the outputted json array to look like User, User instead of ['user1', 'user2']
$users = array();
$result = $db->query('SELECT user_id, ident, u.group_id FROM '.$db->prefix.'online LEFT JOIN '.$db->prefix.'users AS u ON (ident=u.username) WHERE idle=0 ORDER BY ident', true) or error('Unable to fetch online list', __FILE__, __LINE__, $db->error());
while ($user_online = $result->fetch_assoc())
{
$users[] = $user_online["ident"];
}
I tried to use:
$trimmed = trim($users, '[]');
But this threw a warning/error:
PHP Warning: trim() expects parameter 1 to be string
Also tried:
$string = implode('[]', $users);
It does output 2 users, but its formated/outputted like:
user1[]user2
(Moved solution to answer space on behalf of the question author to move it from the question).
Fixed by using:
$string = implode(", ", $users);

PDO fetch returning zero

I have this code which i am testing from last couple of hour but unable to understand that why TodayAttendanceCount is not returning 0.
$sqlCheckLoginEntryCount = "SELECT Count(*) TodayAttendanceCount FROM AttendanceMachineLogin
WHERE Date(RecordAddDateTime) = :RecordAddDateTime
AND TimeTrackId = :TimeTrackId";
$statementEntryCount = $connPDO->prepare($sqlCheckLoginEntryCount);
$queryParams = array(
':TimeTrackId' => $TimeTrackId,
':RecordAddDateTime' => $RecordAddDateTime
);
$statementEntryCount->execute($queryParams);
$queryData = $statementEntryCount->fetch();
echo '\n ';
//var_dump($queryData);
echo "\n Attendance Count". $queryData['TodayAttendanceCount'] ." ;";
I have executed the same query in MySqlWorkbench which is working fine and there is data and it is fine from the database side.
Remove : part at the $queryParams. It isn't needed. The code will look like this.
$queryParams = array(
'TimeTrackId' => $TimeTrackId,
'RecordAddDateTime' => $RecordAddDateTime
);
Try this:
$sqlCheckLoginEntryCount = "SELECT Count(*) As TodayAttendanceCount FROM AttendanceMachineLogin
WHERE Date(RecordAddDateTime) = ':RecordAddDateTime'
AND TimeTrackId = :TimeTrackId";
$statementEntryCount = $connPDO->prepare($sqlCheckLoginEntryCount);
$queryParams = array(
'TimeTrackId' => $TimeTrackId,
'RecordAddDateTime' => $RecordAddDateTime
);
$statementEntryCount->execute($queryParams);
$queryData = $statementEntryCount->fetch(PDO::FETCH_ASSOC);
echo '\n ';
//var_dump($queryData);
echo "\n Attendance Count ". $queryData['TodayAttendanceCount'];
Hope I pushed you further.

Why do my dates not display on this graph (drupal, php, mysql)?

My mission this week has been to create a sales graph for my Drupal 6, Ubercart and Ubercart Marketplace installation.
I settled on the charts_graphs module and decided to use the Bluff library to graph the data. Although the supported module views_charts allows you to create a wide range of charts, it wasn't able to retrieve the dataset that I needed to graph the sales data. If anyone wants the details of why not, just ask and I'll do my best to elaborate.
So I found an example of the php needed to generate a bluff graph:
<?php
$canvas = charts_graphs_get_graph('bluff');
$canvas->title = "Bluff Chart";
$canvas->type = "line"; // a chart type supported by the charting engine. See further in the doc for the list.
$canvas->y_legend = "Y Legend";
$canvas->colour = '#D54C78';
$canvas->theme = 'keynote';
$canvas->series = array(
'Some Value' => array(9,6,7,9,5,7,6,9,7),
'Page Views' => array(6,7,9,5,7,6,9,7,3),
);
$canvas->x_labels = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
$out = $canvas->get_chart();
return $out;
}
?>
This code then generates this graph...
The next stage of course is to get the data from a MySQL query into the graph. This is where I'm outside of my comfort zone because I haven't really done anything previously with PHP.
So after some digging around I found this post with an example that gave me something to work with. I then used views to help get me started with the SQL. I'm so close I can taste it but this last issue has had me snagged and I can't think of any more searches to do... I'm sure you can relate with that feeling :)
So this is the code I've developed so far:
<?php
global $user;
$uname = $user->uid;
$sql = "SELECT DATE_FORMAT((FROM_UNIXTIME(uc_orders.created) + INTERVAL 3600 SECOND), '%d/%m/%Y') as OrderDate, round(SUM(uc_order_products.cost * uc_order_products.qty),2) AS SellerCommission,
round(SUM(uc_order_products.price * uc_order_products.qty),2) AS CustomerPrice
FROM uc_order_products
LEFT JOIN node node_uc_order_products ON uc_order_products.nid = node_uc_order_products.nid
LEFT JOIN uc_orders uc_orders ON uc_order_products.order_id = uc_orders.order_id
INNER JOIN users node_uc_order_products__users ON node_uc_order_products.uid = node_uc_order_products__users.uid
WHERE (node_uc_order_products__users.uid = $uname )
AND (uc_orders.created >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY)))
AND (uc_orders.order_status in ('payment_received', 'completed'))
GROUP BY DAY(FROM_UNIXTIME(uc_orders.created))
ORDER BY MONTH(FROM_UNIXTIME(uc_orders.created)) desc, DAY(FROM_UNIXTIME(uc_orders.created)) desc
LIMIT 31";
$result = db_query($sql,$uname);
while($row = db_fetch_array($result))
{
$sellercommission[] = (int) $row[SellerCommission];
$customerprice[] = (int) $row[CustomerPrice];
$orderdate[] = (string) $row[OrderDate];
}
$canvas = charts_graphs_get_graph('bluff');
$canvas->title = "Volume of sales";
$canvas->type = "line"; // a chart type supported by the charting engine. See further in the doc for the list.
$canvas->y_legend = "Y Legend";
$canvas->colour = '#FFFFFF';
$canvas->width = '450';
$canvas->height = '300';
$canvas->theme = '';
$canvas->series = array(
'Seller Commission' =>array_values($sellercommission),
'Customer price' =>array_values($customerprice),
);
$canvas->x_labels = array_values($orderdate);
$out = $canvas->get_chart();
return $out;
?>
This code generates a perfect graph, all but the x-axis only displays "//" for the dates...
When I run the query on the database this is the result set that I get. Obviously I replace the placeholder with a UID:
09/09/2013 1328.13 1897.32
07/09/2013 455.00 650.00
What I can't work out is the type for "$orderdate[] ...." that I should be using. I've tried varchar, int (displays 0), date (breaks it and displays nothing), datetime (breaks it again)... Or perhaps I am retrieving the wrong data as OrderDate in the SQL. Any ideas would be greatly appreciated...
So I finally worked it out (complete fluke and don't understand the difference) but this is the final code that worked:
<?php
global $user;
$uname = $user->uid;
$sql = "SELECT concat(DAY(FROM_UNIXTIME(uc_orders.created)),'/',MONTH(FROM_UNIXTIME(uc_orders.created)),'/', YEAR(FROM_UNIXTIME(uc_orders.created))) as OrderDate, round(SUM(uc_order_products.cost * uc_order_products.qty),2) AS SellerCommission,
round(SUM(uc_order_products.price * uc_order_products.qty),2) AS CustomerPrice
FROM uc_order_products
LEFT JOIN node node_uc_order_products ON uc_order_products.nid = node_uc_order_products.nid
LEFT JOIN uc_orders uc_orders ON uc_order_products.order_id = uc_orders.order_id
INNER JOIN users node_uc_order_products__users ON node_uc_order_products.uid = node_uc_order_products__users.uid
WHERE (node_uc_order_products__users.uid = $uname )
AND (uc_orders.created >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY)))
AND (uc_orders.order_status in ('payment_received', 'completed'))
GROUP BY DAY(FROM_UNIXTIME(uc_orders.created))
ORDER BY MONTH(FROM_UNIXTIME(uc_orders.created)) desc, DAY(FROM_UNIXTIME(uc_orders.created)) asc
LIMIT 31";
$result = db_query($sql,$uname);
while($row = db_fetch_array($result))
{
$sellercommission[] = (int) $row[SellerCommission];
$customerprice[] = (int) $row[CustomerPrice];
$orderdate[] = (string) $row[OrderDate];
}
$canvas = charts_graphs_get_graph('bluff');
$canvas->title = "Volume of sales";
$canvas->type = "line"; // a chart type supported by the charting engine. See further in the doc for the list.
$canvas->y_legend = "Y Legend";
$canvas->colour = '#FFFFFF';
$canvas->width = '450';
$canvas->height = '300';
$canvas->theme = '';
$canvas->series = array(
'Seller Commission' =>array_values($sellercommission),
'Customer price' =>array_values($customerprice),
);
$canvas->x_labels = array_values($orderdate);
$out = $canvas->get_chart();
return $out;
?>
I basically changed the way I asked for the "OrderDate" in the SQL.... Also corrected a few other minor details...

SELECT COUNT(a.id) AS id... => Result array is empty! [PHP, MySQL]

I'm having trouble with some PHP since yesterday, looked through the web and had the stupid feeling that I'm missing something important.
Using mysql_fetch_object usually, tried it with mysql_fetch_array though (did not help). Here's the part of the code which gives me an headache:
public static function get_datacenter_by_id($id) {
$result = mysql_query("SELECT COUNT(rack.id) AS Racks, COUNT(device.id) AS Devices, COUNT(card.id) AS Cards, COUNT(port.id) AS Ports
FROM datacenter, rack, device, card, port, location, building
WHERE location.id = building.location_id AND
building.id = datacenter.building_id AND
datacenter.id = '.$id.' AND
rack.id = device.rack_id AND
device.id = card.device_id AND
(card.id = port.card_id1 OR
card.id = port.card_id2)") or die ("Error in query: ".mysql_error());
$array = array();
while($row = mysql_fetch_object($result)) {
$array[] = array($row->Racks, $row->Devices, $row->Cards, $row->Ports);
}
return $array;
}
$array is used in another .php file, but using print_r $array already shows you, that the array stays empty (0). I'm quite sure that the error appears in this block of code, could "COUNT (x) AS y" be at fault?
PS: The MySQL Query works, tested it via Workbench before. I'd appreciate some good adivce! :-)
Have a nice day!
Isn't this as simple as:
$result = mysql_query("SELECT COUNT(rack.id) AS Racks, COUNT(device.id) AS Devices, COUNT(card.id) AS Cards, COUNT(port.id) AS Ports
FROM datacenter, rack, device, card, port, location, building
WHERE location.id = building.location_id AND
building.id = datacenter.building_id AND
datacenter.id = '" . $id . "' AND
rack.id = device.rack_id AND
device.id = card.device_id AND
(card.id = port.card_id1 OR
card.id = port.card_id2)") or die ("Error in query: ".mysql_error());
Note the modification from '.$id.' to '" . $id . "'. Your query is looking for a data centre ID of '.$id.'.
Instead of using it like this
while($row = mysql_fetch_object($result)) {
$array[] = array($row->Racks, $row->Devices, $row->Cards, $row->Ports);
}
You should do this
$row = mysql_fetch_object($result)
$array[] = $row->Racks;
$array[] = $row->Devices;
$array[] = $row->Cards;
Because you are fetching 1 record and using it in while is causing problem

access multidimensional array

This is sort of a follow up to my last question. Im trying to access the data of a multidimensional array so as to insert into a database. Ive been looking all over the forums as well as trying different things on my own but cant find anything that works. Here is what the array looks like:
$_POST[] = array[stake](
'stakeholder1' => array(
'partner'=> 'partner',
'meet'=> 'meet'
),
'stakeholder2' => array(
'partner'=> 'partner',
'agreement'=> 'agreement',
'train'=> 'train',
'meet'=> 'meet'
),
);
I'm trying to do somthing like ( UPDATE list WHERE stakeholder = "stakeholder1" SET partner =1, meet =1 ) depending on which stakeholder/choices were selected (theres four different options). Thanks,
This one will set 1 for checked options, and 0 for unchecked options (otherwise you will miss some data updates).
$optionsList = array('partner', 'agreement', 'train', 'meet');
$stakeHolders = array('stakeholder1', 'stakeholder2', ...);
foreach($stakeHolders as $stakeHolder)
{
$selectedOptions = $_POST[$stakeHolder];
$arInsert = array();
foreach($optionsList as $option)
$arInsert[] = '`'.$option.'` = '.intval(isset($selectedOptions[$option]));
$sql = "UPDATE list
SET ".implode(", ", $arInsert)."
WHERE stakeholder = '".mysql_real_escape_string($stakeHolder)."'";
// TODO: execute $sql (mysql_query(), or PDO call,
// or any wrapper you use for DB)
}
$query = '';
foreach ($_POST as $k => $v) {
$query .= "UPDATE list WHERE stakeholder = '$k' SET " . implode(" = 1," $v) . ",";
}
$query = substr($query, 0, -2); //Get rid of the final comma
This should give you something like what you are looking for, if I understand your database schema correctly.
If you are using PDO, you could do something like:
foreach($_POST as $stakeholder => $data) {
$sth = $dbh->prepare('UPDATE `list` SET `' . implode('` = 1, `', array_keys($data)) . '` = 1 WHERE stakeholder = ?');
$sth->execute(array($stakeholder));
}
Be sure to sanitize the user input (keys of the data...).
foreach($main_array as $key => $sub_array) {
$sql = 'UPDATE list
WHERE stakeholder = "{$key}"
SET ';
$sets = array();
foreach($sub_array as $column_value)
$sets[] = $column_value." = 1";
$sql = $sql.implode(',', $sets);
}

Categories