PHP - Help Ammending A Graph Script
hi, I hope some one can be of help?
I want to make a graph using php and GD with data from MySQL, so far success. Now I want to ammend the script (see end of message) to display text on each bar, e.g red, green, blue. Also currently I loop through when setting the bar colours, in this case grey, how can I get it so there are 3 different colours? There will only ever be 3 bars. Thank you for any help Gary Code: [Select] <?php $dbhost = 'host'; $dbuser = 'user'; $dbpass = 'password'; $dbname = 'db'; $tblname = 'tbl'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); // Make a MySQL Connection $query = sql goes here! $result = mysql_query($query) or die(mysql_error()); $values = array(); // Print out result while($row = mysql_fetch_array($result)){ array_push($values,$row['COUNT(Answer)']);} // This array of values is just here for the example. //$values = array("5","6","7"); // Get the total number of columns we are going to plot $columns = count($values); // Get the height and width of the final image $width = 150; $height = 200; // Set the amount of space between each column $padding = 15; // Get the width of 1 column $column_width = $width / $columns ; // Generate the image variables $im = imagecreate($width,$height); $gray = imagecolorallocate ($im,0xcc,0xcc,0xcc); $gray_lite = imagecolorallocate ($im,0xee,0xee,0xee); $gray_dark = imagecolorallocate ($im,0x7f,0x7f,0x7f); $white = imagecolorallocate ($im,0xff,0xff,0xff); // Fill in the background of the image imagefilledrectangle($im,0,0,$width,$height,$white); $maxv = 0; // Calculate the maximum value we are going to plot for($i=0;$i<$columns;$i++)$maxv = max($values[$i],$maxv); // Now plot each column for($i=0;$i<$columns;$i++) { $column_height = ($height / 100) * (( $values[$i] / $maxv) *100); $x1 = $i*$column_width; $y1 = $height-$column_height; $x2 = (($i+1)*$column_width)-$padding; $y2 = $height; imagefilledrectangle($im,$x1,$y1,$x2,$y2,$gray); // imagefilledrectangle($im,$x1,$y1,$x2,$y2,$colour[$i]); // This part is just for 3D effect imageline($im,$x1,$y1,$x1,$y2,$gray_lite); imageline($im,$x1,$y2,$x2,$y2,$gray_lite); imageline($im,$x2,$y1,$x2,$y2,$gray_dark); } // Send the PNG header information. Replace for JPEG or GIF or whatever header ("Content-type: image/png"); imagepng($im); ?> Similar TutorialsHello, I am using a tutorial script for generating a basic bar graph. I have attempted to convert this script into an object-oriented script. However, upon attempting to define the graph, it is not successfully generated. Here is my code: Code: [Select] <? class Graph { var $values; var $image; var $image_width = 450; var $image_height = 300; var $margin = 20; var $bar_size = 20; var $horizontal_lines = 20; var $bar_colour; var $border_colour; var $background_colour; var $line_colour; function CreateGraph() { $this->image = imagecreate($this->image_width, $this->image_height); } function SetSize($width, $height) { $this->image_width = $width; $this->image_height = $height; } function SetMargin($size) { $this->margin = $size; } function SetBarSize($size) { $this->bar_size = $size; } function SetHorLines($size) { $this->horizontal_lines = $size; } function HexConvert($rgb) { return array( base_convert(substr($rgb, 0, 2), 16, 10), base_convert(substr($rgb, 2, 2), 16, 10), base_convert(substr($rgb, 4, 2), 16, 10), ); } function SetColours($bars, $background, $border, $line) { // This is hex based, similar to CSS, it is converted by HexConvert $bars = $this->HexConvert($bars); $background= $this->HexConvert($background); $border= $this->HexConvert($border); $line = $this->HexConvert($line); $this->bar_colour = imagecolorallocate($this->image, $bars[0], $bars[1], $bars[2]); $this->background_colour = imagecolorallocate($this->image, $background[0], $background[1], $background[2]); $this->border_colour = imagecolorallocate($this->image, $border[0], $border[1], $border[2]); $this->line_colour =imagecolorallocate($this->image, $line [0], $line [1], $line [2]); } function DrawBorders() { imagefilledrectangle($this->image,1,1,$this->image_width-2,$this->image_height-2,$this->border_colour); imagefilledrectangle($this->image,$this->margin,$this->margin,$this->image_width-1-$this->margin,$this->image_height-1-$this->margin,$this->background_colour); } function DrawHorLines($horizontal_gap, $ratio) { for($i=1;$i<=$this->horizontal_lines;$i++) { $y = $this->image_height - $this->margin - $horizontal_gap * $i ; imageline($this->image, $this->margin, $y, $this->image_width - $this->margin, $y, $this->line_colour); $v = intval($horizontal_gap * $i / $ratio); imagestring($this->image, 0, 5, $y-5, $v, $this->bar_colour); } } function DrawBars($graph_height, $gap, $ratio) { for($i=0;$i< $total_bars; $i++) { list($key,$value)=each($this->values); $x1= $this->margin + $gap + $i * ($gap+$this->bar_size) ; $x2= $x1 + $this->bar_size; $y1 = $this->margin +$graph_height- intval($value * $ratio) ; $y2 = $this->image_height-$this->margin; imagestring($this->image,0,$x1+3,$y1-10,$value,$this->bar_colour); imagestring($this->image,0,$x1+3,$this->image_height-15,$key,$this->bar_colour); imagefilledrectangle($this->image,$x1,$y1,$x2,$y2,$this->bar_colour); } } function DrawGraph() { $graph_width=$this->image_width - $this->margin * 2; $graph_height=$this->image_height - $this->margin * 2; $total_bars = count($values); $gap = ($graph_width- $total_bars * $this->bar_width ) / ($total_bars +1); $this->DrawBorders(); $max_value=max($values); $ratio = $graph_height / $max_value; $horizontal_gap = $graph_height / $horizontal_lines; $this->DrawHorLines($horizontal_gap, $ratio); $this->DrawBars($graph_height, $gap, $ratio); } function OutputGraph() { header("Content-type:image/png"); imagepng($this->image); } } ?> I expect this to be my misunderstanding of how object orientated codes work. I'm also open to any suggestions for improvement. Edit: Here is the script where I use the class. Code: [Select] <? include "bargraph.class.php"; $graph = new Graph; $graph->SetSize(450, 300); $graph->CreateGraph(); $graph->SetMargin(20); $graph->SetBarSize(20); $graph->SetHorLines(20); $graph->SetColours("FFFFFF", "C0C0C0", "000000", "000000"); $graph->DrawGraph(); $graph->OutputGraph(); ?> Hi Guys I have some code, written by somebody else, which i think updates a 'comments' table when a comment is written on my home page... Code: [Select] <?php include("db.php"); if(isSet($_POST['comentario_valor'])){ $id=time();// Demo Use $comment=$_POST['comentario_valor']; $id=$_POST['id']; $sql=mysql_query("insert into comments(comment,msg_id_fk)values('$comment','$id')"); $result=mysql_query("select * from comments order by com_id desc"); $row=mysql_fetch_array($result); $com_id=$row['com_id']; $comment=$row['comment']; } ?> What i need to do now tho is try to ammend this script to also update the table with the 'userid' of the person who posted the comment. The userid should be the same as in my 'users' table. Can anybody point me in the right direction? I am new to PHP and trying to decipher this peice is code is beyond me at the minute Many thanks hi guys ..I want to create graphs in php. Data will be taken by mysql ofcourse... I have seen lots of options like fusion chart xml, phpgraphlib and so on... my question is What will be the best library or tool. What will be your recommendation to create graphs. Thanks Hi All, Are there any decent PHP graph solutions out there? I have an SQL statement that returns 12 numberical values in an array (mssql_fetch_array). I would like to plot these values on a graph. Thanks Matt I'm working on PHP Math for my assignment, and it requires a graph to show the functions. But, i have no idea how to build a x-y-z (3D) graph.... All codes that i have search only for 2-dimensional (x-y axis) only.. Is there any help or solutions to make a 3-dimensional graph using PHP or Javascript? thank you before Hi everyone, Newish to PHP and I'm sure this is a simple thing but I was hoping someone could help me out. I have a php file that draws a graph for me (it takes in the coordinates from a text file). What I want to do is insert a red line at the top of the graph (not from start to finish, but starting at a certain point in the graph and finishing at another point). This php code achieves the line I would like to insert into the graph: <?php $canvas = imagecreatetruecolor(1000, 10); // Allocate colors $red = imagecolorallocate($canvas, 255, 0, 0); ImageFilledRectangle($canvas, 0, 0, 1000, 10, $red); // Output and free from memory header('Content-Type: image/jpeg'); imagejpeg($canvas); imagedestroy($canvas); ?> I need to insert this into this php script: <?php $width = 1000; //width and height of the resulting image $height = 230; $drawLastLine = false; //draw 9th line or not $testMode = false; //render only 10 images //returns directory with cached images by name of text file function getCacheDirectory($fname) { $mod = filemtime($fname); $dirname = "cache/" . $fname . "." . $mod . "/"; return $dirname; } //checks if specified txt file is cached function isCached($fname) { $dirname = getCacheDirectory($fname); return file_exists($dirname); } //calculated y-coordinates of base-lines for all 9 lines, returns an array function initStart($height, $number = 9) { $d = $number + 1; $t = $height / $d; $res = array(); $c = 0; for ($i = 0; $i < $number; $i++) { $c += $t; $res[$i] = $c; } return $res; } //draws vertical grey line with specified coordinate function drawVerticalLine($img, $x) { $grey = imagecolorallocate($img, 80, 80, 80); $h = imagesy($img); imagesetthickness($img, 3); imageline($img, $x, 0, $x, $h, $grey); imagesetthickness($img, 0.1); } //cuts unfilled part of image in the right, making its width equal to $realW function cutRight($img, $realW) { $h = imagesy($img); $new = imagecreatetruecolor($realW, $h); imagecopy($new, $img, 0, 0, 0, 0, $realW, $h); return $new; } //makes up an array of required colors function allocateColors($img) { $result = array(); $result['blue'] = imagecolorallocate($img, 0, 0, 255); $result['red'] = imagecolorallocate($img, 255, 0, 0); $result['black'] = imagecolorallocate($img, 0, 0, 0); $result['white'] = imagecolorallocate($img, 255, 255, 241); return $result; } //main function which generates all the images function generateImages($fname) { set_time_limit(0); //there's no time limit, because it's long process global $width, $height, $start, $testMode, $drawLastLine; $lines = 9; $start = initStart($height, $drawLastLine ? $lines : $lines - 1); //colors of line from top bo bottom $lineCol = array('blue', 'blue', 'red', 'red', 'blue', 'blue', 'black', 'red', 'red'); $fp = fopen($fname, "r"); //we open our file with data $header = fgets($fp); $curX = 0; $sumX = 0; $imgNum = 1; $colors = false; $const = 1.0; //that's the constant which can be used to multiply by y-coordinates, i.e. making our graphs scalable by y-coordinate $prevY = array(); for ($i = 0; $i < $lines; $i++) { $prevY[$i] = 0; } $dir = getCacheDirectory($fname); mkdir($dir); $img = false; // $maximumImages = 10; //if we are testing, we will do just 10 images, else we will work until the file ends while ((!$testMode || ($testMode && $imgNum < $maximumImages)) && $line = fgets($fp)) { //if it's time to make up a new image if ($sumX % $width == 0) { //we save old one to file if ($img) { imagegif($img, $dir . $imgNum . ".gif"); $imgNum++; } //and create a new one, along with allocating colors and so on $img = imagecreatetruecolor($width, $height); $colors = allocateColors($img); imagefill($img, 0, 0, $colors['white']); $curX = 0; } $data = explode(",", $line); $time = array_shift($data); $linesCount = $drawLastLine ? $lines : $lines - 1; //we loop through our lines for ($i = 0; $i < $linesCount; $i++) { $ly = $data[$i] * $const; //it's the new Y coordinate, and we counts from baseline with y = 0 $realTo = $start[$i] + $ly; //now we count the baseline too $realFrom = $start[$i] + $prevY[$i]; //that's the previous step's y-coordinate $prevY[$i] = $ly; //we remember current coordinate to draw line on next step $x1 = $curX - 1; $y1 = $realFrom; $x2 = $curX; $y2 = $realTo; //we draw line finally with needed color imageline($img, $x1, $y1, $x2, $y2, $colors[$lineCol[$i]]); } //if the time looks like 235.000000, we need to draw vertical line if (round($time) == $time) { drawVerticalLine($img, $curX); } //we increase both curX (which is used for drawing) and overall x (it indicates how much lines we've processed) $curX++; $sumX++; } // if we didn't save all lines to .gifs, we need to save leftovers if ($curX > 0) { $img = cutRight($img, $curX); imagegif($img, $dir . $imgNum . ".gif"); $imgNum++; } //saving numbers of pictures rendered file_put_contents($dir . "info.txt", ($imgNum - 1)); } $fname = $_GET['file']; //there should be no slashes in filename and it should end with .txt if (strpos($fname, "/") !== false || strpos($fname, "\\") !== false || strpos($fname, ".txt") === false) { echo "Security error!"; die; } //it should exist if (!file_exists($fname)) { echo "No such file!"; die; } //if there are no images cached for our file, we need to generate them if (!isCached($fname)) { generateImages($fname); } $page = 1; $dirname = getCacheDirectory($fname); $maxPages = file_get_contents($dirname . "info.txt"); //$maxPages = 10; $uniqid = uniqid(); $img = $dirname . $page . ".gif?" . uniqid(); include("templates/show2.php.inc"); I'm just lost as to how I achive this line in the longer php script. I've tried creating my own function, and then calling it further down but this just breaks it. Any help is appreciated!! I'm trying to get a bar graph from total number of hit on a month to month basis. Everything works out find, except the bar graph is only showing 1 month, not everything that's being pulled out of the db. Can anybody look and see what I'm doing wrong? Code: [Select] $userid = '44'; $t_month = date("Y-m-d h:i:s"); $y_month = date("Y-m-d h:i:s", strtotime("-1 Year")); //Grabs Unique Visitors to App Page $query = "SELECT CONCAT_WS(' ', YEAR(date), MONTHNAME(date)) AS RptDate, COUNT(DISTINCT referrer) 'referrer' FROM app_analytics WHERE appid = $userid AND date BETWEEN '" .$y_month."' AND '" .$t_month."' GROUP BY CONCAT_WS(' ', YEAR(date), MONTHNAME(date)) ORDER BY YEAR(date), MONTH(date)"; $result = mysql_query($query) or die(mysql_error()); //$totals = array(); while($row = mysql_fetch_array( $result )){ $months = date("M", strtotime($row['RptDate'])); $ip = $row['referrer']; $values = array("$months" => $ip); $img_width=450; $img_height=300; $margins=20; # ---- Find the size of graph by substracting the size of borders $graph_width=$img_width - $margins * 2; $graph_height=$img_height - $margins * 2; $img=imagecreate($img_width,$img_height); $bar_width=20; $total_bars=count($values); $gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1); # ------- Define Colors ---------------- $bar_color=imagecolorallocate($img,0,64,128); $background_color=imagecolorallocate($img,240,240,255); $border_color=imagecolorallocate($img,200,200,200); $line_color=imagecolorallocate($img,220,220,220); # ------ Create the border around the graph ------ imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color); imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color); # ------- Max value is required to adjust the scale ------- $max_value=max($values); $ratio= $graph_height/$max_value; # -------- Create scale and draw horizontal lines -------- $horizontal_lines=20; $horizontal_gap=$graph_height/$horizontal_lines; for($i=1;$i<=$horizontal_lines;$i++){ $y=$img_height - $margins - $horizontal_gap * $i ; imageline($img,$margins,$y,$img_width-$margins,$y,$line_color); $v=intval($horizontal_gap * $i /$ratio); imagestring($img,0,5,$y-5,$v,$bar_color); } # ----------- Draw the bars here ------ for($i=0;$i< $total_bars; $i++){ # ------ Extract key and value pair from the current pointer position list($key,$value)=each($values); $x1= $margins + $gap + $i * ($gap+$bar_width) ; $x2= $x1 + $bar_width; $y1=$margins +$graph_height- intval($value * $ratio) ; $y2=$img_height-$margins; imagestring($img,0,$x1+3,$y1-10,$value,$bar_color); imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color); imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color); } header("Content-type:image/png"); imagepng($img); } Thanks in advance Anyone can help me with plotting of multiple line graph in php. I have researched on multiple line graph online and I would like to plot the graph by taking data from my database but the example below is inserting the graph data manually. Anyone can teach me how to use a for loop inside an array? Code: [Select] <?php //Include the code require_once 'phplot.php'; //Define the object $plot = new PHPlot(800,600); //Set titles $plot->SetTitle("A 3-Line Plot\nMade with PHPlot"); $plot->SetXTitle('X Data'); $plot->SetYTitle('Y Data'); //Define some data $example_data = array( array('a',3,4,2), array('b',5,3,1), array('c',7,2,6), array('d',8,1,4), array('e',2,4,6), array('f',6,4,5), array('g',7,2,3) ); $plot->SetDataValues($example_data); //Turn off X axis ticks and labels because they get in the way: $plot->SetXTickLabelPos('none'); $plot->SetXTickPos('none'); //Draw it $plot->DrawGraph(); ?> Following Sams PHP 24hrs... Rewrote Example and it isn't working... I am not getting any syntax error just an error saying it cannot display the graph because there are errors in the image. I have went through it line for line looking for mispellings you name it making sure it was exactly as they wrote so I could follow along... but now its is not working and I believe its me.. not the book... can anyone help me out? <?php //Send content type header to browser so image will be rendered header ("Content-type: image/png"); class SimpleBar { private $xgutter = 20;//left/right margin private $ygutter = 20;//top/bottom margin private $bottomspace = 30;//gap at the bottom private $internalgap = 10;//gap between bars private $cells = array();//labels/amounts for bar charts private $totalwidth; private $totalheight; private $font; function __construct( $width, $height, $font ) { $this->totalwidth = $width; $this->totalheight = $height; $this->font = $font; } //Used to allow user to populate $cells[] property array function addBar( $label, $amount ) { $this->cells[ $label ] = $amount; } private function _getTextSize( $cellwidth ) { $textsize = (int)( $this->bottomspace );//Make $textsize equal to bottomspace if ( $cellwidth < 10 ) { $cellwidth = 10; } //Loop through the cells array and acquire dimension info for the labels using imageTTfbBox() foreach ( $this->cells as $key=>$val ) { while ( true ) { $box = imageTTFbBox( $textsize, 0, $this->font, $key ); $textwidth = abs ( $box[2] ); if ( $textwidth < $cellwidth ) { break; } $textsize--; } } return $textsize; } function draw() { $image = imagecreate( $this->totalwidth, $this->totalheight );//Create Image Resource //Create Color resources $red = imagecolorallocate( $image, 255,0,0 );//Red $blue = imagecolorallocate( $image, 0,0,255 );//Blue $black = imagecolorallocate( $image, 0,0,0 );//Black $max = max( $this->cells );//Cache the maxium value the $cells[] array has $total = count( $this->cells );//Cache the number of elements the $cells[] array contains $graphCanX = ( $this->totalwidth - $this->xgutter*2 );//Set up the canvas space on the X-axis for the graph $graphCanY = ( $this->totalheight - $this->ygutter*2 - $this->bottomspace );//Set up the canvas space on the Y-axis for the graph ( Have to allow room for our labels and margins ) $posX = $this->xgutter;//Store the starting point for drawing our bars on the X-axis $posY = $this->totalheight - $this->ygutter; - $this->bottomspace;//Store the starting point for drawing our bars on the Y-axis ( Have to allow room for our labels and margins ) $cellwidth = (int) ( ( $graphCanX -( $this->internalgap * ( $total - 1 ) ) ) / $total );//Calculate the cellwidth for each bar by taking the width of the graph canvas and subtracting the total distance bewteen the bars divided by the total amount of bars being used $textsize = $this->_getTextSize( $cellwidth ); foreach( $this->cells as $key=>$val ) { $cellheight = (int) ( ( $val/$max ) * $graphCanY );//Calculate height of each bars $center = (int) ( $posX + ($cellwidth/2) );//Calculate cener point of bars $imagefilledrectangle( $image, $posX, ($posY - $cellheight), ($posX+$cellwidth), $posY, $blue);//Draw the bars $box = imageTTFbBox( $textsize, 0, $this->font, $key ); $tw = $box[2]; imageTTFtext( $image, $textsize, 0, ($center-($tw/2) ), ( $this->totalheight-$this->ygutter), $black, $this->font, $key ); $posX += ( $cellwidth + $this->internalgap); } imagepng( $image ); } } $graph = new SimpleBar( 500, 300, "league_gothic-webfont.ttf" ); $graph->addBar("Really Liked" , 200); $graph->addBar("Liked" , 100); $graph->addBar("Kinda Like" , 300); $graph->draw(); ?> I need a simple line graph for my PHP site showing page views against date (monthly). Have tried to find plugins but can't find an appropriate one. Can someone please help with a script or direct me to a plugin. Attached is the kind of graph I'd like to have. For the life of me, I cannot find a way to delete, cancel or remove facebook events I created & updated using the FB PHP SDK & the Graph API. I've tried every single permutation found on facebook's documentation & stack overflow... Here are some of the clues I have found on my quest.. https://developers.facebook.com/docs/reference/api/#deleting https://developers.facebook.com/docs/reference/api/event/ https://developers.facebook.com/docs/reference/rest/events.cancel/ http://stackoverflow.com/questions/2931387/facebook-sdk-and-graph-api-comment-deleting-error http://stackoverflow.com/questions/2858748/facebook-api-delete-status http://stackoverflow.com/questions/3832405/facebook-graph-api-delete-like Here is what I have tried so far. function delete_fb_event($event_data, $data) { //load the user for offline access and userid $user = $this->load_user($data['aid']); if(!empty($user[0]['fb_offline_access'])) { //instantiate Facebook API require 'facebook.php'; $facebook = new Facebook(array( 'appId' => 'BLAHBLAHBLAH', 'secret' => 'BLAHBLAHBLAHBLAHBLAHBLAH', 'cookie' => true, )); $fb_event = array( "access_token" => $user[0]['fb_offline_access'], ); $result = $facebook->api('/'.$event_data['fb_event_id'], 'DELETE', $fb_event); //Uncaught GraphMethodException: Unsupported delete request //$result = $facebook->api('/'.$user[0]['fb_id']."_".$event_data['fb_event_id'], 'POST', array('access_token' => $user[0]['fb_offline_access'], 'method' => 'delete')); Uncaught OAuthException: (#803) Some of the aliases you requested do not exist //$result = $facebook->api('/'.$event_data['fb_event_id']."_".$user[0]['fb_id'], 'POST', array('access_token' => $user[0]['fb_offline_access'], 'method' => 'delete')); Uncaught OAuthException: (#803) Some of the aliases you requested do not exist //$result = $facebook->api('/'.$event_data['fb_event_id'], 'POST', array('access_token' => $user[0]['fb_offline_access'], 'method' => 'delete')); Uncaught GraphMethodException: Unsupported post request //$result = $facebook->api('/'.$user[0]['fb_id']."_".$event_data['fb_event_id'], 'POST', array( 'access_token' => $user[0]['fb_offline_access'], 'method' => 'delete' )); Uncaught OAuthException: (#803) Some of the aliases you requested do not exist return $result; } else { echo "error3"; //no FB offline access } } I have the following code: Code: [Select] private function buildJSResponse(){ $data = ""; $i = 0; $arr = array(); while($this->db->row()){ $arr[] = (int)$this->db->field("average"); } $this->max = max($arr); $this->min = min($arr); $this->mid = round(($this->max + $this->min) / 2); foreach($arr as $val){ $nTime = ($val / $this->max) * 100; $data .= "data[$i] = ".$nTime.";"; $i++; } return $data; } It takes an array, finds the max/min and number halfway between the min/max. The next part I am not sure what to do. I am making a line graph using the canvas, so I am building a javascript array, which will contain the point on the chart. The problem I am having, is location. Lets say $max = 110, and $min = 95. the y position on the graph should be 0 for $max, and 100 for $min, then all the other points need to fall into their place as well. $nTime is supposed to do that, but it doesn't any suggestions? The attachment is the result I am getting from my above code. As you can see the lowest number is 49, so the value with 49 should touch the bottom, which it doesn't. Hello people, currently i ran into some problem. Currently, i have a database called responses which have the fields of ID, Student_id, question_id, Answer. I had stored my results into the database which appeared to be 1 1 1 Agree 2 1 2 Disagree 3 3 4 Unsatisfied. So any recommendation on how should i do about in generating the result into a graph whereby the graph will show how many students choose "AGree" on that particular question THANKS Retrieve Pages, Ads, Leads from multiple facebook accounts with Graph API - Help needed Hi everyone! I've been working on a php script to replace links that contain a query with direct links to the files they would redirect to. I'm having trouble echoing $year in my script. Listed below is the script, just below ,$result = mysql_query("SELECT * FROM $dbname WHERE class LIKE '%$search%'") or die(mysql_error());, in the script I try to echo $year. It doesn't show up in the table on the webpage. Everything else works fine. Any help wold be appreciated greatly. Thanks in advance. <?php include 'config2.php'; $search=$_GET["search"]; // Connect to server and select database. mysql_connect($dbhost, $dbuser, $dbpass)or die("cannot connect"); mysql_select_db("vetman")or die("cannot select DB"); $result = mysql_query("SELECT * FROM $dbname WHERE class LIKE '%$search%'") or die(mysql_error()); // store the record of the "" table into $row //$current = ''; echo "<table align=center border=1>"; echo "<br>"; echo "<tr>"; echo "<td align=center>"; ?> <div style="float: center;"><a><h1><?php echo $year; ?></h1></a></div> <?php echo "</td>"; echo "</tr>"; echo "</table>"; // keeps getting the next row until there are no more to get if($result && mysql_num_rows($result) > 0) { $i = 0; $max_columns = 2; echo "<table align=center>"; echo "<br>"; while($row = mysql_fetch_array($result)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; echo "<td align=center>"; ?> <div style="float: left;"> <div><img src="<?php echo $image1; ?>"></div> </div> <?php echo "</td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i > 0) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; echo '</tr>'; } mysql_close(); ?> </table> Hi i have this upload script which works fine it uploads image to a specified folder and sends the the details to the database. but now i am trying to instead make a modify script which is Update set so i tried to change insert to update but didnt work can someone help me out please this my insert image script which works fine but want to change to modify instead Code: [Select] <?php mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("upload") or die(mysql_error()) ; // my file the name of the input area on the form type is the extension of the file //echo $_FILES["myfile"]["type"]; //myfile is the name of the input area on the form $name = $_FILES["image"] ["name"]; // name of the file $type = $_FILES["image"]["type"]; //type of the file $size = $_FILES["image"]["size"]; //the size of the file $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name $error =array(); // this an empty array where you can then call on all of the error messages $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values $location = 'images/'; //location of the file or directory where the file will be stored $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg //echo $extension = substr($name, 3); //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg // another way of doing is with explode // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode $myfile = $_POST["myfile"]; if (isset($image)) // if you choose a file name do the if bellow { // if extension is not equal to any of the variables in the array $allowed_exts error appears if(in_array($extension, $allowed_exts) === false ) { $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line } // if file type is not equal to any of the variables in array $image_type error appears if(in_array($type, $image_type) === false) { $error[] = 'Type of file not allowed! only images allowed<br />'; } // if file bigger than the number bellow error message if($size > 2097152) { $error[] = 'File size must be under 2MB!'; } // check if folder exist in the server if(!file_exists ($location)) { $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location; } } // if no error found do the move upload function if (empty($error)){ if (move_uploaded_file($temp, $location .$appendic_name)) { // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image mysql_query("INSERT INTO image (myfile ,image) VALUES ('$myfile', '$appendic_name')") ; exit(); } } else { foreach ($error as $error) { echo $error; } } //echo $type; ?> hey guys im really just after a bit of help/information on 2 things (hope its in the right forum).
1. basically I'm wanting to make payments from one account to another online...like paypal does...im wondering what I would need to do to be able to do this if anyone can shine some light please?
2.as seen on google you type in a query in the search bar and it generates sentences/keywords from a database
example:
so if product "chair" was in the database
whilst typing "ch" it would show "chair" for a possible match
I know it would in tale sql & json but im after a good tutorial/script of some sort.
if anyone can help with some information/sites it would be much appreciated.
Thank you
I'm trying to use this script known as SimpleImage.php that can be found here <a href="http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php">link</a> I'm trying to include what is on the bottom of the page to my existing script can anyone help me I've tried several ways but its not working. Code: [Select] <?php session_start(); error_reporting(E_ALL); ini_set('display_errors','On'); //error_reporting(E_ALL); // image upload folder $image_folder = 'images/classified/'; // fieldnames in form $all_file_fields = array('image1', 'image2' ,'image3', 'image4'); // allowed filetypes $file_types = array('jpg','gif','png'); // max filesize 5mb $max_size = 5000000; //echo'<pre>';print_r($_FILES);exit; $time = time(); $count = 1; foreach($all_file_fields as $fieldname){ if($_FILES[$fieldname]['name'] != ''){ $type = substr($_FILES[$fieldname]['name'], -3, 3); // check filetype if(in_array(strtolower($type), $file_types)){ //check filesize if($_FILES[$fieldname]['size']>$max_size){ $error = "File too big. Max filesize is ".$max_size." MB"; }else{ // new filename $filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type; // move/upload file $target_path = $image_folder.basename($filename); move_uploaded_file($_FILES[$fieldname]['tmp_name'], $target_path); //save array with filenames $images[$count] = $image_folder.$filename; $count = $count+1; }//end if }else{ $error = "Please use jpg, gif, png files"; }//end if }//end if }//end foreach if($error != ''){ echo $error; }else{ /* -------------------------------------------------------------------------------------------------- SAVE TO DATABASE ------------------------------------------------------------------------------------ -------------------------------------------------------------------------------------------------- */ ?> Hello, I stored a fsockopen function in a separate "called.php" file, in order to run it as another thread when it needs. The called script should return results to the "master.php" script. I'm able to run the script to get the socket working, and I'm able to get results from the called script. I tried for hours but I can't do the twice both My master.php script (with socket working): Code: [Select] <?php $command = "(/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR] &) > /dev/null"; $result = exec($command); echo ("result = $result\r\n"); ?> and my called.php script Code: [Select] #!/mnt/opt/usr/bin/php-cli -q <?php $device = $_SERVER['argv'][1]; $port = "8080"; $fp = fsockopen($device, $port, $errno, $errstr, 5); fwrite($fp, "test"); fclose($fp); echo ("normal end of the called.php script"); ?> In the master script, if I use Code: [Select] $command = "(/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR] &) > /dev/null"; the socket works, but I have nothing in $result (note also that I don't anderstand why the ( ... &) are needed!?) and if I use Code: [Select] $command = "/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR]"; I have the correct text "normal end of the called.php script" in $result but the socket connection is not performed (no errors in php logs) Could you help me to find a way to let's work the two features correctly together? Thank you. |